Menü Schließen

Data Binding to Visibility Property

The following describes how to used a converter to directly bind your ViewModel properties to the Visibility of controls in your view.

First we define a converter that converts a boolean value into a Visibility enum value and back.

[ValueConversion(typeof(bool), typeof(Visibility))]
public class VisibilityConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    if (value == null)
      return null;
    bool b = (bool)value;
    if (b)
      return Visibility.Visible;
    else
      return Visibility.Collapsed;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    Visibility vValue = (Visibility)value;
    if (vValue == Visibility.Collapsed || vValue == Visibility.Hidden)
      return false;
    return true;
  }
}

Define the converter in the resources of your view:

<Application.Resources>
  <ResourceDictionary>
    <converters:VisibilityConverter x:Key="VisibilityConverter" />
  </ResourceDictionary>
</Application.Resources>

Bind the Visibility of your view elements to the VM properties, using the converter:

<TreeViewItem IsExpanded="True" Visibility="{Binding BasicDataMenuVisible, Converter={StaticResource VisibilityConverter}}"/>

 

Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert