MVVM - hiding a control when bound property is not present

前端 未结 1 1122
不知归路
不知归路 2020-12-11 00:52

I was wondering if it is possible to hide a control on a view if the property to which the control is bound does not exist in the view model. For example, if I have the fol

相关标签:
1条回答
  • 2020-12-11 01:55

    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
    }
    
    0 讨论(0)
提交回复
热议问题