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



我对 c# 中的 mvvm 和 wpf 真的很陌生,并且被困在一些非常基本的东西上。在这个例子中,我使用的是Fody.PropertyChanged。我有一个基本的视图模型,其中包含一个名为 Test 的字符串,该字符串绑定到文本块。

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(( 函数时,如何更新视图模型中的测试变量?例如,单击按钮时

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 中,模型不会更新视图模型,实际上相反,视图模型更新模型属性。

下面是一个示例。

型:

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;
}
}

您的视图将绑定到您的视图模型。

更新:关于您的问题

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";
}
}

最新更新