Question

I'm trying to apply a DataTrigger to a Button and it depends on a property from the currently selected item of a TreeView. The idea is that I want to change the text of a Button depending on a property of the selected item.

What I have looks like this:

<Button x:Name="m_AddObject" Margin="192.708,0.909,6,6.363" Click="AddObject_Click" >
    <DataTrigger Binding="{Binding ElementName=ObjectTreeView, Path=SelectedItem.Removable}" Value="true">
        <Setter TargetName="m_AddObject" Property="Content" Value="Remove" />
    </DataTrigger>
</Button>

But I can't get it to compile. The Setter complains about "Content" not being valid because it doesn't have a qualifying type name, but if I change it to "Button.Content" it then complains of "Object reference not set to an instance of an object".

I also tried:

<Setter TargetName="m_AddObject.Content" Value="Remove" />

While that compiles, it didn't work either.

I'm stumped.

Any ideas?

Thanks!

Was it helpful?

Solution

DataTriggers should be defined in a Style for the button. What you're trying to do above is essentially use a DataTriggers as the "label" (the "Content", as WPF puts it) for the button (instead of, say, "OK").

This is ad-hoc, so it might not be totally correct, but it's closer to what you want:

<Button x:Name="m_AddObject"
        Margin="192.708,0.909,6,6.363"
        Click="AddObject_Click">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=ObjectTreeView, Path=SelectedItem.Removable}" Value="True">
                    <Setter Property="Content" Value="Remove" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top