【问题标题】:C#: How to Bind Button.Enabled to Whether If There Is Any Item Selected of a ListViewC#:如何将 Button.Enabled 绑定到 ListView 是否有任何项目被选中
【发布时间】:2011-04-29 17:27:48
【问题描述】:

我有一个关于 Control.DataBindings 的问题。

如何将 Button.Enabled 绑定到 ListView 是否有任何项目被选中?即:

Button.Enabled = ListView.SelectedItems.Count > 0;

我知道我可以使用 ListView.SelectionChanged 事件来做到这一点。

我只是想知道如何使用 DataBinding 来完成同样的工作。

谢谢。

彼得

P.S.:我想这样做的原因是:如果 Button.Enabled 取决于很多其他控件的条件,我认为 DataBinding 更简单。

【问题讨论】:

  • 你会将它绑定到什么?我会按照您的建议使用 SelectionChanged 事件。
  • 如果只有 WPF/Silverlight 就好了……

标签: c# data-binding controls properties


【解决方案1】:

如果您想使用绑定,您需要创建一个 ValueConverter。这是通过实现System.Windows.Data.IValueConverter 接口来完成的(MSDN 页面有一个示例实现)。如果传入的 int 大于 0,则在其中返回 true。

在您的情况下,您可以将Button.Enabled 绑定到ListView.SelectedItems.Count,并指定您的值转换器。

正如@PaulG 在 cmets 中所说,使用 SelectionChanged 事件可能更容易,但可以通过绑定来实现。

【讨论】:

    【解决方案2】:

    我通常先尝试触发器,然后再尝试值转换器。
    在这种情况下,您实际上不必实现值转换器,只需一个简单的 DataTrigger 即可:

    <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>
    

    【讨论】:

      猜你喜欢
      • 2015-10-02
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      相关资源
      最近更新 更多