如果ListBox选择了项目,WPF如何绑定其他控件的IsEnabled属性?

3
我有一个包含两列的网格,第一列是列表框,第二列是主网格中的其他控件。我希望只有当通过绑定选择了列表框中的项目时,这些控件才能启用(或者可能可见)。我在组合框上尝试过:
IsEnabled="{Binding myList.SelectedIndex}"

但是这似乎不起作用。
我有什么遗漏吗?像这样的东西应该能行吗?
谢谢。
3个回答

6
您需要一个 ValueConverter 来实现这个功能。 这篇文章 对其进行了详细说明,但总结起来,您需要一个公共类来实现 IValueConverter 接口。在 Convert() 方法中,您可以这样做:
if(!(value is int)) return false;
if(value == -1) return false;
return true;

现在,在您的XAML中,您需要这样做:
<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并检查非空可能更容易,但这只是个人偏好。

哦,如果你不熟悉备用的xmlns声明,在你的Window顶部添加:

xmlns:local=

当你使用VS时,它会提示你各种可能性。你需要找到与你所创建的值转换器所在的命名空间匹配的那一个。


2

复制粘贴的解决方案:

将此类添加到您的代码中:

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();
    }
}

<Application.Resources>部分将转换器作为静态资源添加到App.xml中:
<local:HasSelectedItemConverter x:Key="HasSelectedItemConverter" />

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

<Button IsEnabled="{Binding ElementName=listView1, Path=SelectedIndex,
 Converter={StaticResource HasSelectedItemConverter}"/>

0

嗯,也许可以使用BindingConverter,将所有大于0的索引显式转换为true。


ListBox的索引值为0是有效的,但如果要判断是否有选中项,需要使用if > -1。 - JustABill

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