有 8 个按钮,分别命名为、DrawMoneyFromChannel1
等。DrawMoneyFromChannel2
DrawMoneyFromChannel3
每个频道上都有一个List<DeviceChannels>
包含金额的金额。
如果相应频道的金额为零,则不应启用相应频道的按钮。
在这种情况下组织绑定的最佳方法是什么?
不要在 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
并具有一个 property Amount
、一个 propertyName
和一个Draw
property ICommand
。已ICommand
实现,所以当为零CanExecute
时为假。Amount