如果基础 DataContext 为空,如何隐藏控件? [英] How to hide a control if the underlying DataContext is null?

查看:16
本文介绍了如果基础 DataContext 为空,如何隐藏控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图模型中有一个对象,它有一堆属性,其中一些偶尔会为空.如果这些特定控件为空,我不想只显示一些控件.如果绑定为空,我将如何隐藏控件?我正在考虑某种转换器,但不知道我将如何去做.有什么想法吗?

I have an object in my view model that has a bunch of properties, some of them will occasionally be null. I don't want to just show some controls if these particular controls are null. How would I go about hiding the control if the bind is null? I was thinking of some sort of converter, but don't know how I'd go about doing it exactly. Any ideas?

抱歉,我应该提到这也将在 Silverlight 中,所以我不确定样式触发器是否会起作用......?

edit: sorry, I should mention that this will also be in Silverlight, so I'm not sure if Style triggers would work...?

推荐答案

有一个如下的转换器,

public sealed class NullToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null ? Visibility.Hidden: Visibility.Visible;
    }

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

现在,将该属性也与 Visibility 属性绑定.喜欢,

Now, bind the property with the Visibility property as well. Like,

<ListBox ItemsSource="{Binding Path=Squad}" 
         Visibility="{Binding Converter={StaticResource nullToVisibilityConverter}, 
                              Path=Squad}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这篇关于如果基础 DataContext 为空,如何隐藏控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆