Question

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?

Was it helpful?

Solution

The answer is pretty simple:

Binding="{Binding RelativeSource={RelativeSource Self}, Path=(v:ExtensionHelper.OperationMode)}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top