7

SetProperty ref - The object is null

 3 years ago
source link: https://www.codesd.com/item/setproperty-ref-the-object-is-null.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

SetProperty ref - The object is null

advertisements

I guess it's just a really small thing I'm overlooking, but I can't figure out why this won't work...

public ObservableCollection<UserDto> Users
{
    get
    {
        return _users;
    }
    set
    {
        SetProperty(ref _users, value);
    }
}

Now when I set Users like this, it will still be null:

pageItem.Object.Users = new ObservableCollection<UserDto>();

I can get it working if I use a "standard" Property like this:

public ObservableCollection<UserDto> Users { get; set; }

But why does it not work with SetProperty(ref variable, value)?

I'm using .NET Framework 4.5.

I also debugged the code. In the first screenshot, _users is null and I try to set a value which contains one UserDto:

var newUsers = new ObservableCollection<UserDto>();
var user = new UserDto();
newUsers.Add(user);
pageItem.Object.Users = newUsers;  // This steps into the setter

After this step tho, _users is still null:


SetProperty is not a built-in method. If the _users field is still null after calling this method, the method is obviously incorrectly implemented.

You could take a look at how the SetProperty method is actually implemented in Prism and compare this implementation to yours:

protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
    if (Equals(storage, value)) return false;

    storage = value;
    RaisePropertyChanged(propertyName);

    return true;
}

https://github.com/PrismLibrary/Prism/blob/master/Source/Prism/Mvvm/BindableBase.cs

For testing purposes, you could paste in the above implementation into your class, give the method another name and call this one instead of the current SetProperty method.

If you are using Prism's version of SetProperty it should work though. If it doesn't you should prove your point: https://stackoverflow.com/help/mcve


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK