【发布时间】:2013-12-29 22:21:08
【问题描述】:
考虑以下样式:
<Window.Resources>
<Style x:Key="NumberButton" TargetType="Button">
<Setter Property="Width" Value="Auto"/>
<Setter Property="Height" Value="Auto"/>
<Setter Property="Margin" Value="2"/>
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Label Content="{Binding}" FontSize="20" FontFamily="Consolas"/>
</DataTemplate>
</Setter.Value>
</Setter>
<EventSetter Event="Click" Handler="OnClicked"/>
</Style>
</Window.Resources>
我的目标是能够创建多个按钮,每个按钮代表一个数字 0-9。例如,这里是数字 0 的按钮:
<Button Grid.Row="3" Grid.Column="1" Style="{StaticResource NumberButton}" Content="0"/>
我对 DataContext 工作原理的理解是,如果您没有在 XAML 中显式设置它,它应该是 NULL,它指示绑定改为使用父级的 DataContext。这是传递性的,因此它会继续向上移动每个父级,直到找到要使用的明确设置的 DataContext。
然而,我对我的绑定如何映射到Content 属性感到困惑。我知道ContentControl 的默认属性是Content 属性,但我从未在<Button> 元素上明确设置DataContext。对我来说,这意味着 Button 的 DataContext 为 NULL,因此它无法找到要显示的值。
谁能解释一下我没有设置 Button 的 DataContext 是如何被引用的?
【问题讨论】: