MVVM - 隐藏控件时绑定属性不是present [英] MVVM - hiding a control when bound property is not present

查看:141
本文介绍了MVVM - 隐藏控件时绑定属性不是present的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有可能隐藏在视图控制如该控件绑定的属性不会在视图模型存在。举例来说,如果我有以下几点:

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 following:

<CheckBox Content="Quote"
          IsChecked="{Binding Path=IsQuoted}" />

我可以检测XAML的IsQuoted属性不会对视图模型存在,只是隐藏在该实例的控制。

Can I detect in XAML that the IsQuoted property does not exist on the view model, and simply hide the control in that instance.

我本质上是创建通过视图模型集合动作,显示为每一个相关的视图向导对话框。对于一些集合中的视图模型,有IsQuoted属性​​将是present,对于一些没有。

I am essentially creating a wizard dialog that moves through a collection of view models, displaying the associated view for each one. For some of the view models in the collection, the "IsQuoted" property will be present, and for some not.

我想有这些意见之外的复选框,显示在当前视图模型具有属性,当视图模型不隐藏。所有视图模型都是从一个共同的基类派生的,但我宁愿不加入一个ShowQuoted财产等杂乱的基础。

I would like to have a check box outside of these views that displays when the current view model has the property, and hides when the view model does not. All of the view models are derived from a common base class, but I would rather not clutter the base by adding a "ShowQuoted" property, etc.

的思考?而且,在此先感谢...

Thoughts? And, thanks in advance...

推荐答案

处理它的价值通过使用转换器,它总是返回Visibility.Visible是present的情况。处理这种情况的值不是指定一个后备价值present的情况。当财产不是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
}

这篇关于MVVM - 隐藏控件时绑定属性不是present的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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