c#mvvm代码简单案例
时间: 2023-11-23 14:05:08 浏览: 102
以下是一个简单的C# MVVM模式的案例:
Model类:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
```
ViewModel类:
```csharp
public class PersonViewModel : INotifyPropertyChanged
{
private Person _person;
public Person Person
{
get { return _person; }
set
{
_person = value;
OnPropertyChanged("Person");
}
}
public PersonViewModel()
{
Person = new Person();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
View:(XAML)
```xaml
<Window x:Class="MVVMDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMDemo"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<TextBox Text="{Binding Person.Name}" />
<TextBox Text="{Binding Person.Age}" />
</StackPanel>
</Grid>
</Window>
```
在View的代码behind中指定DataContext为ViewModel:
```csharp
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new PersonViewModel();
}
}
```
这个案例中,当View中的TextBox的Text属性绑定到ViewModel中的Person的Name和Age属性时,当这些属性的值改变时,View中的TextBox会自动更新。这就是MVVM模式的核心思想。
阅读全文