Search code examples
wpfmvvmwpfdatagrid

Set the Visibility of Data Grid in WPF


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.

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}" >

In my view model I am setting IsGridVisible value

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

Please provide your ideas. Thanks


Solution

  • 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.

    Visible Display the element.

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