闽公网安备 35020302035485号
<StackPanel DataContext="Hello, world" TextBlock.FontSize="22">
<StackPanel.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontWeight" Value="Bold" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</StackPanel.Resources>
<TextBlock Text="{Binding}" />
</StackPanel>
代码示例中TextBlock的属性有不少依赖:TextBlock.Text依赖于绑定(Binding),而这里的绑定(Binding)依赖于DataContext,DataContext是从父元素StackPanel继承下来的,因此,TextBlock.Text也依赖于树的形状;如果TextBlock从StackPanel移除,StackPanel的值也会发生变化。
TextBlock.FontSize也依赖于树。在这里,你可以看到它从StackPanel继承。
所有的TextBlock属性都依赖于TextBlock.style。例如,这里是TextBlock.FontWeight来自样式(Style)。
同样的,TextBlock.Background也依赖样式(Style)。但在这个示例中,它在触发器(Trigger)中设置。所以TextBlock.Background在这种情况下也取决于TextBlock.IsMouseOver。
public int Foo
{
get { return (int)GetValue(FooProperty); }
set { SetValue(FooProperty, value); }
}
// Using a DependencyProperty as the backing store for Foo. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FooProperty =
DependencyProperty.Register("Foo", typeof(int), typeof(Window1), new PropertyMetadata(FooChangedCallback));
// 堆代码 duidaima.com
static void FooChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
// Whenever Foo changes, we need to invalidate FooPlus1, so that
// the DependencyProperty system knows to update it (call its
// CoerceValueCallback again).
(d as Window1).InvalidateProperty(Window1.FooPlus1Property);
}
public int FooPlus1
{
get { return (int)GetValue(FooPlus1Property); }
}
static readonly DependencyPropertyKey FooPlus1PropertyKey =
DependencyProperty.RegisterReadOnly("FooPlus1", typeof(int), typeof(Window1), new PropertyMetadata(0, null, CoerceFooPlus1Callback));
static readonly DependencyProperty FooPlus1Property = FooPlus1PropertyKey.DependencyProperty;
static object CoerceFooPlus1Callback(DependencyObject d, object baseValue)
{
return (d as Window1).Foo + 1;
}