What's wrong with my datatrigger binding?

北城余情 提交于 2019-12-10 23:23:10

问题


I have created an attached property to extend a Button class with additional state:

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

Then I want to access this value in the ControlTemplate using DataTrigger like this:

<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>

But I get this error:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.Button', AncestorLevel='1''. BindingExpression:Path=(0); DataItem=null; target element is 'Button' (Name=''); target property is 'NoTarget' (type 'Object')

The binding expression in the DataTrigger seems to be incorrect. What am I doing wrong?


回答1:


The answer is pretty simple:

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


来源:https://stackoverflow.com/questions/1728159/whats-wrong-with-my-datatrigger-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!