【问题标题】:WPF Conditional Binding. Button.IsEnabled to SelectedIndex >= 0WPF 条件绑定。 Button.IsEnabled 到 SelectedIndex >= 0
【发布时间】:2011-02-23 23:29:15
【问题描述】:

我想将按钮IsEnabled 属性绑定到myObject.SelectedIndex >= 0 之类的条件。有没有一种简单的方法可以在 xaml 中执行此操作(无需对任何底层对象做疯狂的事情)?我还没有真正看到一个很好的例子。

老实说,我希望这和 Flex 3 一样简单...... I.E.:

<mx:Button enabled="{dataGrid.SelectedIndex >= 0}" ...

【问题讨论】:

    标签: wpf data-binding xaml binding


    【解决方案1】:

    如果没有选择,SelectedIndex 是 -1,对吗?反转你的逻辑并使用触发器:

    <Button ...>
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="enabled" Value="True" />
    
                <Style.Triggers>
                    <DataTrigger
                        Binding="{Binding SelectedIndex,ElementName=dataGrid}"
                        Value="-1">
    
                        <Setter Property="IsEnabled" Value="False" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        <Button.Style>
    <Button>
    

    【讨论】:

    • 谢谢,我可以将它用于我的一个按钮,但另一个将是 SelectedIndex >= 1 的位置。我可以像上面的示例那样使用 MultiDataTrigger 吗?
    • MultiDataTrigger 用于将条件与运算结合在一起时使用。要执行 SelectedIndex>=1,请复制“-1”的数据触发器并将触发器值更改为“0”。
    【解决方案2】:

    我还没有找到一种特别易于使用的方法来将表达式嵌入到 XAML 中,所以这是我一直在使用的方法:

    BindingOperations.SetBinding(myBtn, Button.IsEnabledProperty, LambdaBinding.New(
        new Binding { Source = myObject,
                      Path = new PropertyPath(ComboBox.SelectedIndexProperty) },
        (int selectedIndex) => selectedIndex >= 0
    ));
    

    您必须在 C# 中编写此代码,例如在窗口的构造函数中。

    这也适用于多源绑定:

    BindingOperations.SetBinding(myBtn, Button.IsEnabledProperty, LambdaBinding.New(
        new Binding { Source = myObject,
                      Path = new PropertyPath(ComboBox.SelectedIndexProperty) },
        new Binding { Source = myObject2,
                      Path = new PropertyPath(Button.ActualHeightProperty) },
        (int selectedIndex, double height) => selectedIndex >= 0 && height > 10.5
    ));
    

    观察 lambda 是静态类型的,任何类型错误都是(相对)嘈杂的,有助于追踪它们。还考虑了 lambda 返回类型;您可以使用它来将一个对象的宽度绑定为基于另一个对象宽度的复杂公式...

    这个LambdaBinding 类不是内置的;您必须包含 LambdaBinding.cs 文件。

    旁注。 XAML 不允许表达式真是太遗憾了。是的,我意识到 XAML 应该是“为设计师设计的”,并且没有我们称之为应用程序逻辑的这种难以捉摸的东西,但我们在这里开什么玩笑......首先,另一个中显示的 DataTrigger answer 基本上是一个条件表达式,因此与{Binding source.SelectedIndex &gt;= 0} 没有什么不同(只是 长)。其次,如果想法很简单,那么设计人员应该能够编写的绑定表达式远远超出了非程序员的能力……如果您需要证明,请考虑以下内容:

    {Binding RelativeSource={RelativeSource AncestorType={x:Type UIElement}, 
                                            AncestorLevel=1},
             Path=IsEnabled}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-23
      • 2012-08-23
      • 2011-01-06
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      相关资源
      最近更新 更多