I have a question about Control.DataBindings.
How can I bind Button.Enabled to whether if there is any item selected of a ListView? i.e.:
Button.Enabled = ListView.SelectedItems.Count > 0;
I know that I can use ListView.SelectionChanged event to do this.
I'm just wondering how can I use DataBinding to do the same job.
Thanks.
P开发者_运维百科eter
P.S.: The reason I want to do this is: if Button.Enabled is depending on the conditions of a lot of other controls, I think DataBinding is simpler.
If you want to use bindings, you'd need to create a ValueConverter. This is done by implementing the System.Windows.Data.IValueConverter interface (the MSDN page has an example implementation). In it you would return true if the int
passed in is greater than 0.
In your case, you would bind Button.Enabled
to ListView.SelectedItems.Count
, and specify your value converter.
As @PaulG said in the comments, it is possibly easier to just use the SelectionChanged
event, but it is possible to do via bindings.
I usually try triggers first then value converters.
You don't actually have to implement a value converter in this case, a simple DataTriggger will do:
<Button>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Setters>
<Setter Property="Content" Value="Enabled When Selection Changed"/>
</Style.Setters>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=_listBox, Path=SelectedItems.Count}"
Value="0">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
<ListBox x:Name="_listBox">
<ListBox.Items>
<ListBoxItem Content="1"/>
<ListBoxItem Content="2"/>
</ListBox.Items>
</ListBox>
精彩评论