Say I have a WPF XAML code as below
<Grid>
<Grid.ColumnDefinition>
<!--2 Columns are defined-->
</Grid.ColumnDefinition>
<Button x:Name="button" Grid.Column="1"/>
<ListBox x:Name="listBox" Grid.Column="2"/>
</Grid>
Now, each li开发者_C百科stboxitems are bound to an object of a class with a member named "Status". Whenever an item is selected, Status becomes "0". If un-selected status becomes "1".
Now, my question is, how do I disable/enable the button (in XAML)whenever any of the items "Status" becomes "0" or "1" respectively. Is there a way to do this via DataTriggers
Thanks
That depends on where this code is. If it is inside a DataTemplate or ControlTemplate you can use a DataTrigger. If not (or even if it is), you should be able to get the same effect with a direct binding. In either case you can use the same basic method. If you create an IValueConverter that takes in listBox's items (collection of your data objects) and outputs a boolean based on the Status values you can use that to bind button's IsEnabled, or check the value in a DataTrigger and disable as needed.
If you're referring to ListBox selection when you say selected/un-selected then the you don't even need to look at the Status values themselves. If you're inside a template (can use Triggers) you could also just check whether listBox has any selected items:
<DataTrigger Binding="{Binding ElementName=listBox, Path=SelectedItems.Count}" Value="0">
<Setter TargetName="button" Property="IsEnabled" Value="False" />
</DataTrigger>
Could you use the Selection_Changed event handler?
Just be sure to make a corresponding trigger for enabling the button when value is 1. Ardman, you can use the Selection_Changed event handler, but I always try to do as much as possible in the XAML and keep UI alterations out of the code behind. Sometimes it works, every now and then it does not.
Cory
精彩评论