代码之家  ›  专栏  ›  技术社区  ›  Chris Klepeis

WPF条件绑定。Button.i启用SelectedIndex>=0

  •  9
  • Chris Klepeis  · 技术社区  · 16 年前

    IsEnabled 属性设置为 myObject.SelectedIndex >= 0

    老实说,我希望这像Flex3一样简单。。。即。:

    <mx:Button enabled="{dataGrid.SelectedIndex >= 0}" ...
    
    2 回复  |  直到 12 年前
        1
  •  17
  •   sergtk    10 年前

    如果未选择任何内容,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>
    
        2
  •  2
  •   Roman Starkov    13 年前

    我还没有找到一种特别易于使用的方法将表达式嵌入到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}
    
    推荐文章