使用 ValueConverter WPF 网格 IsEnabled

发布于 2024-10-16 14:29:28 字数 953 浏览 7 评论 0原文

我有一个带有 Grid 和 TreeView 的 WPF 窗口。网格的数据上下文绑定到树视图上的选定项目。但是,由于并非所有 Treeviewitem 都适用,因此如果 treviewitem 不适用,我想禁用网格。因此,我创建了一个值转换器来执行空检查并返回布尔值。 (在这种情况下,适用的项目不会为空)

问题是从未使用值转换器。我设置了断点,但它们从未被击中。我正在使用其他值转换器,它们都工作得很好。

我有什么遗漏的吗?

<Grid Grid.Column="1" Grid.Row="0" DataContext="{Binding MyVal}" IsEnabled="{Binding MyVal, Converter={StaticResource NullCheckConverter}}" Margin="2,2,2,2">

这对于这个问题来说并不重要,但这里是 ValueConverter 代码:

internal class NullCheckValueConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !(value == null);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

I have a WPF window with a Grid and a TreeView. The datacontext for the Grid is bound to the selected item on the treeview. However, because not all treeviewitems are applicable, I want to disable the grid if the treviewitem isn't applicable. So, I created a value converter to do a null check and return a bool. (Applicable items would not be null in this case)

The problem is that the value converter is never used. I set break points and they are never hit. I have other value converters I'm using and they all work just fine.

Is there something I'm missing?

<Grid Grid.Column="1" Grid.Row="0" DataContext="{Binding MyVal}" IsEnabled="{Binding MyVal, Converter={StaticResource NullCheckConverter}}" Margin="2,2,2,2">

Not that it's important for this question but here is the ValueConverter code:

internal class NullCheckValueConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !(value == null);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

大海や 2024-10-23 14:29:28

这是因为您将 DataContext 绑定到与绑定 IsEnabled 相同的值。因此,对于 IsEnabled 它实际上是在寻找 MyVal.MyVal。替换为:

IsEnabled="{Binding Converter={StaticResource NullCheckConverter}}" 

此外,如果您遇到绑定问题,请在调试模式输出窗口中检查绑定错误。

That's because you bind DataContext to the same value as you binding IsEnabled. So for IsEnabled it actually looking for MyVal.MyVal. Replace to:

IsEnabled="{Binding Converter={StaticResource NullCheckConverter}}" 

Also further if you have issues with binding, check in debug mode output window for binding errors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文