Search code examples
c#wpfmvvmviewmodelfody-propertychanged

C# MVVM How to update viewmodel string from the model


I am really new to mvvm and wpf in c# and got stuck at some very basic stuff.In this example I am using Fody.PropertyChanged. I have a basic viewmodel that holds a string called Test which is binded to a textblock.

 public class Model : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };

        public string Test { get; set; }
    }

Then,in a separate file and class called Data,I have a simple function that increments an int and converts it to a string.

public class Data
    {
        public static int i = 0;
        public static string IncTest { get; set; }
        public static void Inc()
        {
            i++;
            IncTest = i.ToString();
        }
    }

How do I update the Test variable inside the viewmodel when calling the Inc() function? For example, when clicking a button

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new Model();
        Data.Inc();
    }

    private void Increment_Click(object sender, RoutedEventArgs e)
    {
        Data.Inc();
    }

Solution

  • In MVVM, the model does not update the view model, its actually opposite, The view model updates the model properties.

    Here is an example.

    MODEL:

    public class Model
    {
        public string Test
        {
            get;
            set;
        }
    }
    

    View Model:

    public class ViewModel : INotifyPropertyChanged
    {
        private Model _model;
    
        public string Test
        {
            get
            {
                return _model.Test;
            }
            set
            {
                if(string.Equals(value, _model.Test, StringComparison.CurrentCulture))
                {
                    return;
                }
                _model.Test = value;
                OnPropertyChanged();
            }
        }
    
        public ViewModel(Model model)
        {
            _model = model;
        }
    
    }
    

    Your views will bind to your view models.

    UPDATE: In regards to your question

    public class SomeClass
    {
        public static void Main(string [] args)
        {
            Model model = new Model();
            ViewModel viewModel = new ViewModel(model);
    
            //Now setting the viewmodel.Test will update the model property
            viewModel.Test = "This is a test";
        }
    }