【问题标题】:How to bind a set of button's IsEnabled to the specified logic?如何将一组按钮的 IsEnabled 绑定到指定的逻辑?
【发布时间】:2012-11-21 20:43:08
【问题描述】:

共有 8 个按钮,分别命名为 DrawMoneyFromChannel1DrawMoneyFromChannel2DrawMoneyFromChannel3 等。

有一个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>
    

    在本例中,ChannelsChannelViewModel 对象的集合。 ChannelViewModel 类实现了INotifyPropertyChanged 并具有属性Amount、属性Name 和属性Draw,即ICommandICommand 已实现,因此当 Amount 为零时,CanExecute 为 false。

    【讨论】:

    • 原来所有按钮都依赖于一个CanExecute?
    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多