MVVM - hiding a control when bound property is not present MVVM - hiding a control when bound property is not present wpf wpf

MVVM - hiding a control when bound property is not present


Handle the case where it the value is present by using a converter which always returns Visibility.Visible. Handle the case where the value isn't present by specifying a fallback value. When the property isn't present the binding fails and receives the fallback value.

<Page.DataContext>    <Samples:OptionalPropertyViewModel/></Page.DataContext><Grid>    <Grid.Resources>        <Samples:AlwaysVisibleConverter x:Key="AlwaysVisibleConverter" />    </Grid.Resources>    <CheckBox         Content="Is quoted"         IsChecked="{Binding IsQuoted}"        Visibility="{Binding IsQuoted,                      Converter={StaticResource AlwaysVisibleConverter},                      FallbackValue=Collapsed}"        /></Grid>public class OptionalPropertyViewModel{    public bool IsQuoted { get; set; }}public class AlwaysVisibleConverter : IValueConverter{    #region Implementation of IValueConverter    public object Convert(object value,                           Type targetType, object parameter, CultureInfo culture)    {        return Visibility.Visible;    }    public object ConvertBack(object value, Type targetType,                               object parameter, CultureInfo culture)    {        throw new NotImplementedException();    }    #endregion}