【问题标题】:How to bind a set of button's IsEnabled to the specified logic?如何将一组按钮的 IsEnabled 绑定到指定的逻辑?
【发布时间】:2012-11-21 20:43:08
【问题描述】:
共有 8 个按钮,分别命名为 DrawMoneyFromChannel1、DrawMoneyFromChannel2、DrawMoneyFromChannel3 等。
有一个List<DeviceChannels>,其中包含每个频道的金额。
如果相应频道的金额为零,则不应启用相应频道的按钮。
在这种情况下组织绑定的最佳方式是什么?
【问题讨论】:
标签:
wpf
button
binding
isenabled
【解决方案1】:
不要在 XAML 中硬编码按钮:
<!-- BAD -->
<StackPanel>
<Button x:Name="DrawMoneyFromChannel1" Click="??"
Content="Draw money from channel 1" IsEnabled="??"/>
<Button x:Name="DrawMoneyFromChannel2" Click="??"
Content="Draw money from channel 2" IsEnabled="??"/>
<Button x:Name="DrawMoneyFromChannel3" Click="??"
Content="Draw money from channel 3" IsEnabled="??"/>
<Button x:Name="DrawMoneyFromChannel4" Click="??"
Content="Draw money from channel 4" IsEnabled="??"/>
<!-- ... -->
</StackPanel>
<!-- BETTER -->
<ItemsControl ItemsSource="{Binding Channels}">
<ItemsControl.ItemTemplate>
<Button Command="{Binding Draw}">
<TextBlock>
<TextBlock Text="Draw money from "/>
<TextBlock Text="{Binding Name}"/>
</TextBlock>
</Button>
</ItemsControl.ItemTemplate>
</ItemsControl>
在本例中,Channels 是 ChannelViewModel 对象的集合。 ChannelViewModel 类实现了INotifyPropertyChanged 并具有属性Amount、属性Name 和属性Draw,即ICommand。 ICommand 已实现,因此当 Amount 为零时,CanExecute 为 false。