代码之家  ›  专栏  ›  技术社区  ›  Gern Blanston

如果列表框具有选择项,则在其他控件上启用WPF绑定

  •  2
  • Gern Blanston  · 技术社区  · 16 年前

    我有一个2列的网格,第0列有一个列表框,主网格第1列有一个辅助网格中的许多其他控件。

    我希望仅当通过绑定在列表框中选择某个项时,才启用(或者可能可见)此控件。我试过一个组合框:

    IsEnabled="{Binding myList.SelectedIndex}"
    

    但这似乎不起作用。

    我错过什么了吗?像这样的工作需要吗?

    3 回复  |  直到 13 年前
        1
  •  5
  •   JustABill    16 年前

    你需要一个 ValueConverter 为了这个。 This article 详细描述了它,但总结是您需要一个实现IValueConverter的公共类。在Convert()方法中,可以执行以下操作:

    if(!(value is int)) return false;
    if(value == -1) return false;
    return true;
    

    <Window.Resources>
        <local:YourValueConverter x:Key="MyValueConverter">
    </Window.Resources>
    

    最后,将您的绑定修改为:

    IsEnabled="{Binding myList.SelectedIndex, Converter={StaticResource MyValueConverter}"
    

    IsEnabled="{Binding ElementName=myList, Path=SelectedIndex, Converter={StaticResource MyValueConverter}"
    

    尽管如此?不能将元素的名称隐式地放在路径中(除非 Window 它本身就是 DataContext 我想是的)。绑定到SelectedItem并检查NOTNULL可能更容易,但这实际上只是首选项。

    哦,如果你不熟悉alternate xmlns 窗口 添加

    xmlns:local=
    

        2
  •  2
  •   stil    10 年前

    复制粘贴解决方案:

    public class HasSelectedItemConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value is int && ((int) value != -1);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    将转换器作为StaticResource添加到中的App.xml <Application.Resources>

    <local:HasSelectedItemConverter x:Key="HasSelectedItemConverter" />
    

    现在,您可以在XAML中使用它:

    <Button IsEnabled="{Binding ElementName=listView1, Path=SelectedIndex,
     Converter={StaticResource HasSelectedItemConverter}"/>
    
        3
  •  0
  •   DHN    16 年前