0
votes

I have a Tree View

<TreeView HorizontalAlignment="Stretch" Name="tvLocations" VerticalAlignment="Stretch" />

And a button

        <Button Name="cmdUpdateLocation" Grid.Row="1" Content="Update" Width="80" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,88,0">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=tvLocations, Path=SelectedItem}" Value="{x:Null}">
                        <Setter Property="IsEnabled" Value="False"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>

This will enable the button no matter what level of the tree they click on. I want to enable the button when an item in the tree view is selected but only if it is the root node or disable the button if it is not the root. Can I detect in XAML if the node they have selected is the root node?

2

2 Answers

1
votes

I'm afraid not directly. If your TreeView.Items are of type TreeViewItem you could use the solution described here: WPF Treeview root node.

<Style TargetType="{x:Type Button}">
    <Setter Property="IsEnabled" Value="False" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding ElementName=tvLocations, Path=SelectedItem.(local:MyTreeView.IsRootNode)}" Value="True">
            <Setter Property="IsEnabled" Value="True" />
        </DataTrigger>
    </Style.Triggers>
</Style>

If your TreeView.Items are of any other type I think you have to implement an additional IsRootNode property for your items.

1
votes

I have found an alternate solution that does not require code behind. Use a trigger with a binding that looks for an ancestor of the TreeViewItem type and triggers when it equals {x:Null}. This will fire for the root node as it has no TreeViewItem ancestor. The following example trigger prevents the root node from being collapsed:

<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TreeViewItem}}}" Value="{x:Null}">
    <Setter Property="Visibility" Value="Visible" TargetName="ItemsHost" />
</DataTrigger>