[英]WPF Conditional Binding. Button.IsEnabled to SelectedIndex >= 0
我想将按钮IsEnabled
属性绑定到像myObject.SelectedIndex >= 0
的条件。 有没有一种简单的方法在xaml中执行此操作(不必对任何底层对象做疯狂的事情)? 我还没有看到一个很好的例子。
老实说,我希望这就像Flex 3一样容易...... IE:
<mx:Button enabled="{dataGrid.SelectedIndex >= 0}" ...
如果没有选择,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>
我还没有找到一种特别容易使用的方法将表达式嵌入到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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.