简体   繁体   中英

Does my property update my field or am I using MVVM incorrectly

I'm trying to figure out MVVM and WPF and I wanted to test some easy code to get the hang of it.

I've done this before so I thought that this wouldn't be a problem but I'm losing my mind cause of this.

This is not the full code but I've toned it down just for the specific problem

I have a model

private string _btnName;
public string BtnName { get {return _btnName;} set{ _btnName = value; } }

And my view model like this

BtnName {get { return model.BtnName;} set{ model.BtnName = value;}}
ICommand ChangeButtonName = new RelayCommand(ChangeName)

Public void ChangeName(object a){ BtnName = "test"; }

And the view like this

<Button Content={Binding MV.BtnName} Command={Binding MV.ChangeButtonName}/>

Where MV is my ViewModel Class and model is my Model Class.

When I click on the button it goes into my function and does indeed "change" name, but on the view the button will still have the old content. Meaning that it doesn't update.

And I don't understand why.

  • Why does my button not update the content text?
  • Should I have properties in my ViewModel?

You have to implement INotifyPropertyChanged in your ViewModel.

public class MainViewModel : INotifyPropertyChanged
{
    public RelayCommand DoSomethingCommand { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

And you have to change your property to notify your View when the property was updated.

private string _btnName;
public string BtnName { get { return _btnName; } set { _btnName = value; OnPropertyChanged("BtnName"); } }

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