简体   繁体   中英

MVVM Binding, Object Property Notification changed

Relativly new to the MVVM stuff, i have Trouble with the following:

I have an object "User", this object exposes some properties, like Username, Email, etc.. In the mvvm model i have a property:

    private IUser currentUser;
    public IUser CurrentUser
    {
        get
        {
            return this.currentUser;
        }
        set
        {
            this.currentUser = value;
            this.OnPropertyChanged("CurrentUser");
        }
    }

    private void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

In XAML a TextBox is bound as follows:

Text="{Binding CurrentUser.Email, Mode=TwoWay}"

When changing the Email Address the OnPropertyChanged is not fired and thus other code (as the ICommands) are not "working".

Is there a way that when the user changes the Text in the TextBox the OnPropertyChanged fires??

TIA, Paul

You are firing PropertyChanged when CurrentUser changes, but current user is not changing you are just changing the Email property on it. A quick fix could be to have the Email property propagate the OnChange event for CurrentUser.

public string Email
{
    //get
    set
    {
        this.email = value;
        this.OnPropertyChanged("CurrentUser");
    }
}

Actually I think this.OnPropertyChanged("Email") would work too, but the setter of CurrentUser is definitely not getting called when you change a property of it.

Where is your INotifyPropertyChanged Interface? I think it is necessary.

Property Change Notification does not watch the properties of your IUser class. It is only watching for changes to the ViewModel Property CurrentUser (the reference).

You need

a) make the IUser implement INotifyPropertyChanged

or

b) pull out EmailAddress and add it to the ViewModel like so:

 public string Email
    {
        get
        {
            return this.CurrentUser.Email;
        }
        set
        {
            this.CurrentUser.Email = value;
            this.OnPropertyChanged("Email");
        }
    }

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