I have a treeview and a button.
I want to disable the button (IsEnabled=false) when there is NO item selected in the treeview (and I want to enable the button when there is an 开发者_高级运维item selected...).
How can I do this?
Here is my XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
x:Class="WpfApplicationTreeViewTest.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480" WindowStartupLocation="CenterScreen" Margin="40" >
<StackPanel>
<TreeView x:Name="strategyTreeView" Margin="10 40 10 10">
<TreeViewItem Header="Test"></TreeViewItem>
<TreeViewItem Header="Test"></TreeViewItem>
<TreeViewItem Header="Test"></TreeViewItem>
<TreeViewItem Header="Test"></TreeViewItem>
</TreeView>
<Button Name="Panel" Content="Selected" Height="40" Width="100" Margin="10"/>
</StackPanel>
</Window>
You can achieve this with a trigger on the button like this:
<StackPanel>
<TreeView x:Name="strategyTreeView" Margin="10 40 10 10">
<TreeViewItem Header="Test"></TreeViewItem>
<TreeViewItem Header="Test"></TreeViewItem>
<TreeViewItem Header="Test"></TreeViewItem>
<TreeViewItem Header="Test"></TreeViewItem>
</TreeView>
<Button Name="Panel" Content="Selected" Height="40" Width="100" Margin="10">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=strategyTreeView, Path=SelectedItem}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</StackPanel>
Initially you have to disable the Button as after being loaded, the control will have no selection, by using this XAML...
<Button Name="Panel" Content="Selected" Height="40" Width="100" Margin="10" IsEnabled="False"/>
After this you can handle the SelectedItemChanged
of the TreeView
and enable or disable the button from the method, like this:
XAML:
<TreeView x:Name="strategyTreeView" Margin="10 40 10 10" SelectedItemChanged="strategyTreeView_SelectedItemChanged">
Code behind:
private void strategyTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (e.NewValue != null)
Panel.IsEnabled = true;
}
精彩评论