我有一个包含两列的网格,第一列是列表框,第二列是主网格中的其他控件。我希望只有当通过绑定选择了列表框中的项目时,这些控件才能启用(或者可能可见)。我在组合框上尝试过:
但是这似乎不起作用。
我有什么遗漏吗?像这样的东西应该能行吗?
谢谢。
IsEnabled="{Binding myList.SelectedIndex}"
但是这似乎不起作用。
我有什么遗漏吗?像这样的东西应该能行吗?
谢谢。
IsEnabled="{Binding myList.SelectedIndex}"
ValueConverter
来实现这个功能。 这篇文章 对其进行了详细说明,但总结起来,您需要一个公共类来实现 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并检查非空可能更容易,但这只是个人偏好。
哦,如果你不熟悉备用的xmlns
声明,在你的Window
顶部添加:
xmlns:local=
当你使用VS时,它会提示你各种可能性。你需要找到与你所创建的值转换器所在的命名空间匹配的那一个。
复制粘贴的解决方案:
将此类添加到您的代码中:
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}"/>
嗯,也许可以使用BindingConverter,将所有大于0的索引显式转换为true。