我还没有找到一种特别易于使用的方法来将表达式嵌入到 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 >= 0} 没有什么不同(只是多 长)。其次,如果想法很简单,那么设计人员应该能够编写的绑定表达式远远超出了非程序员的能力……如果您需要证明,请考虑以下内容:
{Binding RelativeSource={RelativeSource AncestorType={x:Type UIElement},
AncestorLevel=1},
Path=IsEnabled}