简体   繁体   中英

MVVM Binding To Property == Null

I want to show some elements when a property is not null. What is the best way of achieving this?

The following is my 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()

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

    <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). Would I need to create a custom converter to check for null and return the correct visibility or is there one in .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.

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.

You can also use DataTriggers to do pretty much the same thing without the converter...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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