I have a treeview and a delete button, I want the delete button to be enabled only if a treeview item is selected.
I have tried the following but it doesn't work:
<Button.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=tv_cats, Path=Items.IndexOf(SelectedItem)}" Value="-1">
<Setter Property="Button.IsEnabled" Value="false" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
to test - in code behind -
tv_cats.Items.IndexOf(tv_cats.SelectedItem).ToString()
Returns -1 if tv item not selected and tv items index if it is.
How can I use this property in XAML?
Couple of ways to do this,
Through triggers on the button that evaluate the selectedItem property of the TreeView (Button is enabled by default, Enabled is false when SelectedItem="{x:Null}"
An element property binding from button.Enabled to TreeView.SelectedItem through a converter (Implements IValueConverter) that converts the item existence to a boolean value.
In MVVM, you can have a ButtonIsEnabled property exposed on your ViewModel which checks the value of the SelectedItem in some fashion (Easiest is to have the TreeViews Selected Item property bound to another property on the VIewModel as well) and determing enabled status from that.