简体   繁体   English

MVVM绑定到属性==空

[英]MVVM Binding To Property == Null

I want to show some elements when a property is not null. 我想在属性不为null时显示一些元素。 What is the best way of achieving this? 实现此目标的最佳方法是什么?

The following is my ViewModel: 以下是我的ViewModel:

class ViewModel : ViewModelBase
{
    public Trade Trade
    {
        get { return _trade; }
        set { SetField(ref _trade, value, () => Trade); }
    } private Trade _trade;
}

ViewModelBase inherits INotifyPropertyChanged and contains SetField() ViewModelBase继承INotifyPropertyChanged并包含SetField()

The Following is the Trade class: 以下是贸易类:

public class Trade : INotifyPropertyChaged
{
    public virtual Company Company
    {
        get { return _company; }
        set { SetField(ref _company, value, () => Company); }
    } private Company _company;
    ......
}

This is part of my View.xaml 这是我的View.xaml的一部分

    <GroupBox Visibility="{Binding Path=Trade.Company, 
                           Converter={StaticResource boolToVisConverter}}" />

I would like this groupbox to show only if Trade.Company is not null (so when a user selects a company). 我希望仅当Trade.Company不为null时才显示此组框(因此,当用户选择公司时)。 Would I need to create a custom converter to check for null and return the correct visibility or is there one in .NET? 我是否需要创建一个自定义转换器来检查null并返回正确的可见性,或者.NET中是否存在此可见性?

Rather than using a BooleanToVisibilityConverter , you'll need to use a different converter (one you'll have to write) that will return the appropriate visibility value if the bound value is null. 除了使用BooleanToVisibilityConverter ,您需要使用其他转换器(必须编写一个转换器),如果绑定值为null,它将返回适当的可见性值。

Something like this: 像这样:

public class NullValueToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
                          CultureInfo culture)
    {
        return (value != null ? Visibility.Visible : Visibility.Collapsed);
    }

    public object ConvertBack(object value, Type targetType, object parameter,  
                              CultureInfo culture)
    {
        return null; // this shouldn't ever happen, since 
                     // you'll need to ensure one-way binding
    }
}

You'll need to add Mode = OneWay to your binding, since you won't be able to make a round-trip conversion. 您将需要在绑定中添加Mode = OneWay ,因为您将无法进行往返转换。

You can also use DataTriggers to do pretty much the same thing without the converter... 您也可以使用DataTriggers在没有转换器的情况下做几乎相同的事情...

<GroupBox DataContext="{Binding Path=Trade.Company}">
    <GroupBox.Style TargetType="GroupBox">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=.}" Value="{x:Null}">
                <Setter Property="Visibility" Value="Collapsed"/>
            </DataTrigger>
        </Style.Triggers>
    </GroupBoxStyle>
</GroupBox>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM