我的datatrigger绑定有什么问题?

时间:2009-11-13 09:32:56

标签: wpf data-binding controltemplate datatrigger attached-properties

我创建了一个附加属性来扩展具有附加状态的Button类:

<Button v:ExtensionHelper.OperationMode="{Binding MyObject.OperationMode}" 
        Command="{Binding MyObject.Select}" 
        Style="{StaticResource operationModeControlTemplateStyle}" />

然后,我想使用ControlTemplateDataTrigger中访问此值,如下所示:

<Style x:Key="operationModeControlTemplateStyle" TargetType="Button">
    <Setter Property="IsHitTestVisible" Value="true" />        
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid>
                    <Image x:Name="hand" Source="hand.png" />
                    <Image x:Name="cross" Source="cross.png" />
                </Grid>
                <ControlTemplate.Triggers>
                    <DataTrigger Binding="{Binding Path=(v:ExtensionHelper.OperationMode), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" Value="Manual">
                        <Setter TargetName="cross" Property="Visibility" Value="Collapsed" />
                        <Setter TargetName="hand" Property="Visibility" Value="Visible" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Path=(v:ExtensionHelper.OperationMode), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" Value="Disabled">
                        <Setter TargetName="cross" Property="Visibility" Value="Visible" />
                        <Setter TargetName="hand" Property="Visibility" Value="Collapsed" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Path=(v:ExtensionHelper.OperationMode), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" Value="Automatic">
                        <Setter TargetName="cross" Property="Visibility" Value="Collapsed" />
                        <Setter TargetName="hand" Property="Visibility" Value="Collapsed" />
                    </DataTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

但是我收到了这个错误:

  

System.Windows.Data错误:4:不能   找到与参考绑定的源   'RelativeSource FindAncestor,   AncestorType = 'System.Windows.Controls.Button',   AncestorLevel = '1'”。   BindingExpression:路径=(0);   的DataItem = NULL;目标元素是   'Button'(Name ='');目标属性是   'NoTarget'(输入'Object')

DataTrigger中的绑定表达式似乎不正确。我做错了什么?

1 个答案:

答案 0 :(得分:15)

答案很简单:

Binding="{Binding RelativeSource={RelativeSource Self}, Path=(v:ExtensionHelper.OperationMode)}"