C# MVVM 如何从模型更新 View 模型字符串

标签 c# wpf mvvm viewmodel fody-propertychanged

我对 c# 中的 mvvm 和 wpf 真的很陌生,并且陷入了一些非常基本的东西。在这个例子中,我使用的是 Fody.PropertyChanged。我有一个基本的 View 模型,它包含一个名为 Test 的字符串,该字符串绑定(bind)到一个文本 block 。

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

        public string Test { get; set; }
    }

然后,在一个名为 Data 的单独文件和类中,我有一个简单的函数,它增加一个 int 并将其转换为一个字符串。
public class Data
    {
        public static int i = 0;
        public static string IncTest { get; set; }
        public static void Inc()
        {
            i++;
            IncTest = i.ToString();
        }
    }

调用 Inc() 函数时如何更新 View 模型中的测试变量?例如,当单击按钮时
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new Model();
        Data.Inc();
    }

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

最佳答案

在 MVVM 中,模型不会更新 View 模型,实际上相反, View 模型会更新模型属性。

这是一个例子。

型号:

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

查看型号:
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;
    }

}

您的 View 将绑定(bind)到您的 View 模型。

更新:关于您的问题
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";
    }
}

关于C# MVVM 如何从模型更新 View 模型字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51902682/

相关文章:

WPF 组合框 : how to set focus on it's togglebutton

c# - WPF MVVM 仅在用户确认后更新源属性

c# - 读取XML后,更改颜色不会影响属性更改

c# - Xceed DataGrid SelectedItem问题

c# - 基础提供者在打开时失败/该操作对交易状态无效

c# - 纯数字文本框

c# - 从字符串数组中删除所有空元素

wpf - DataGrid 最后一列后的尾随空格

xaml - 使用MVVM将ScrollIntoView转换为SelectedItem(Windows Phone 8.1)

c# - "Access to the path ' a-guid.8Event ' is denied."启动时