简体   繁体   中英

Checking if no item is selected in checkbox MVVM

I have a button command which can only be executed in this case:

  public bool CanClick
        {
            get
            {
                return (DateX.HasValue) &&
                       (DateY.HasValue) && !string.IsNullOrEmpty(Str.NomStr)

            }

        }

The ComboBox SelectedItem is bound to:

 private Structure _str;
    public Structure Str
    {
        get { return _str; }
        set
        {
            _str = value;
            NotifyOfPropertyChange("Str");
        }
    }

Once I start filling fields (the dates etc.), I get the error saying that

Object reference not set to an instance of an object.' Str.get returned null

The question is why I'm getting this if I'm actually checking If it's null or not?

Because you didn't initialization your _str object, _str will point to NULL

when you get Str you can check if==null , then set a default value.

private Structure _str;
public Structure Str
{
    get {
        if(_str == null)
           _str = new Structure();
        return _str; 
    }
    set
    {
        _str = value;
        NotifyOfPropertyChange("Str");
    }
}

EDIT

if Str==null didn't set value, it means can't click.

You can try to use this code

Because the && need to let right side and left side condition be true .

the right side is false it will return false . will not execute left side condition.

public bool CanClick
{
    get
    {
        return (DateX.HasValue) &&
               (DateY.HasValue) && (Str!=null && !string.IsNullOrEmpty(Str.NomStr))
    }
}

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