在 WPF 中设置数据网格的可见性 [英] Set the Visibility of Data Grid in WPF

查看:31
本文介绍了在 WPF 中设置数据网格的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我在一个 xaml 文件中有 3 个数据网格.根据用户选择,我想显示一个网格并隐藏其他网格.

In my application I have 3 data grids in a single xaml file. Based on the User selection I want show one grid and hide other grids.

在我的视图模型类中,每个网格都有布尔属性,并根据选择将其设置为 true 或 false.但所有网格都是可见的.

in my view model class I have Boolean property for each grid and based on the selection I am setting it to true or false.But all grids are visible .

    <DataGrid  Visibility="{Binding Path=IsGridVisible}" >

在我的视图模型中,我正在设置 IsGridVisible 值

In my view model I am setting IsGridVisible value

public bool IsCapexGridVisible
    {
        get { return isCapexGridVisible; }
        set { isCapexGridVisible = value; RaisePropertyChangedEvent("IsCapexGridVisible"); }
    }

请提供您的想法.谢谢

推荐答案

UIElement 上的可见性属性不是布尔值.它是一个具有三个值的枚举:

Visibility property on UIElement is not a boolean. It is an enum with three values:

折叠不显示元素,也不在布局中为其预留空间.

Collapsed Do not display the element, and do not reserve space for it in layout.

隐藏不显示元素,但在布局中为元素保留空间.

Hidden Do not display the element, but reserve space for the element in layout.

可见显示元素.

因此,为了从 ViewModel 正确设置它,您应该:- 使您的财产类型可见(不是世界上最好的解决方案)- 使用转换器进行绑定,这将完成将布尔值转换为可见性的技巧

So in order to set it properly from ViewModel you should: - make your property type of Visibility (not best solution in the world) - Use converter for the binding which will do the trick of translating boolean to visibility

  public class BooleanToCollapsedConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType == typeof(Visibility) && value is bool)
        {
            return (bool)value ? Visibility.Visible : Visibility.Collapsed;
        }
        throw new FormatException();
    }

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

这篇关于在 WPF 中设置数据网格的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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