访问应用了样式的元素的DataContext

时间:2013-12-30 05:18:06

标签: c# wpf

我有以下XAML(部分):

<Window.DataContext>
    <local:CalculatorViewModel/>
</Window.DataContext>

<Window.Resources>
    <Style x:Key="CalcButton" 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>
        <Setter Property="Command" Value="{Binding CalcButtonPressed}"/>
        <Setter Property="CommandParameter" Value="{Binding}"/>
    </Style>
</Window.Resources>

问题是我在样式中设置CommandParameter。我想将Content的值(这只是一个简单的数字0-9)传递给我的命令函数。奇怪的是,我能够将命令绑定到CalculatorViewModel(在我的Window.DataContext中),但我不知道如何设置CommandParameter绑定以引用回{ {1}}将应用此样式的元素(这是一个Button)。

在样式中的DataContext内,我可以指定<DataTemplate>来访问Button的DataContext。我仍在学习DataContext继承行为,当你将样式抛入混合时,会让事情变得混乱。我假设Styles忽略了正常的继承,而是在物理上放置DataContext信息的样式之外。

1 个答案:

答案 0 :(得分:0)

你需要像这样的setter来传递Button的Content属性:

<Setter Property="CommandParameter" Value="{Binding Content,
                                    RelativeSource={RelativeSource Self}}"/>

<强>解释

  1. 如果您只是{Binding},那么它将传递给作为CalculatorViewModel实例的Button的DataContext

  2. 如果你{Binding Content} - 它将在Button的DataContext中搜索Content属性,即在CalcualtorViewModel中搜索。

  3. 因此,对于RelativeSource={RelativeSource Self},您告诉绑定引擎在按钮上查找属性Content而不是在其DataContext中。

  4. 默认情况下,{Binding Path=AnyProperty}会在其DataContext中搜索AnyProperty