WPF条件绑定。将Button.IsEnabled绑定到SelectedIndex >= 0。

9
我希望能将一个按钮的IsEnabled属性绑定到一个条件上,比如myObject.SelectedIndex >= 0。在xaml中有没有一种简单的方法可以做到这一点(而不必对任何底层对象做出疯狂的修改)?我还没有看到过一个好的例子。
老实说,我希望这能像Flex 3那样容易...例如:
<mx:Button enabled="{dataGrid.SelectedIndex >= 0}" ...
2个回答

18

如果没有选中任何内容,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吗? - Chris Klepeis
1
MultiDataTrigger用于将条件与运算。要执行SelectedIndex>=1,复制'-1'的datatrigger并将触发器值更改为'0'。 - Cameron MacFarland

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基本上是一个条件表达式,因此与{Binding source.SelectedIndex >= 0}没有区别(只是要长得多)。其次,如果想法是简单性,则设计师应该能够编写的绑定表达式远远超出非程序员的能力范围...如果您需要证明,请考虑以下内容:
{Binding RelativeSource={RelativeSource AncestorType={x:Type UIElement}, 
                                        AncestorLevel=1},
         Path=IsEnabled}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接