做動(dòng)態(tài)網(wǎng)站不需要DW嗎推廣技巧
1. MVVM模式概述
MVVM模式由三個(gè)主要部分組成:
- Model(模型):包含應(yīng)用程序的業(yè)務(wù)邏輯和數(shù)據(jù)。通常是數(shù)據(jù)對(duì)象和數(shù)據(jù)訪問層。
- View(視圖):用戶界面部分,展示數(shù)據(jù)并與用戶進(jìn)行交互。通常是XAML文件。
- ViewModel(視圖模型):視圖與模型之間的橋梁。它從Model中獲取數(shù)據(jù)并準(zhǔn)備好讓View使用,同時(shí)處理用戶的交互。
2. MVVM模式在WPF中的實(shí)現(xiàn)
2.1 Model? ?Model: Person.cs
Model通常是數(shù)據(jù)實(shí)體類和數(shù)據(jù)訪問層,可以從數(shù)據(jù)庫或服務(wù)中獲取數(shù)據(jù)。下面是一個(gè)簡單的Model示例:
public class Person
{public string Name { get; set; }public int Age { get; set; }
}
2.2 ViewModel? ?ViewModel: PersonViewModel.cs
ViewModel負(fù)責(zé)從Model獲取數(shù)據(jù)并準(zhǔn)備好供View使用。ViewModel通常實(shí)現(xiàn)INotifyPropertyChanged
接口,以便通知View屬性值的變化。
using System.ComponentModel;public class PersonViewModel : INotifyPropertyChanged
{private Person _person;public PersonViewModel(){_person = new Person { Name = "John Doe", Age = 30 };}public string Name{get { return _person.Name; }set{if (_person.Name != value){_person.Name = value;OnPropertyChanged("Name");}}}public int Age{get { return _person.Age; }set{if (_person.Age != value){_person.Age = value;OnPropertyChanged("Age");}}}public event PropertyChangedEventHandler PropertyChanged;protected void OnPropertyChanged(string propertyName){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}
}
2.3 View? ?View: MainWindow.xaml
View是用戶界面部分,使用XAML定義界面布局和綁定。下面是一個(gè)簡單的View示例:
<Window x:Class="MVVMExample.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MainWindow" Height="200" Width="400"><Grid><StackPanel><TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" /><TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}" /><TextBlock Text="{Binding Name}" /><TextBlock Text="{Binding Age}" /></StackPanel></Grid>
</Window>
2.4 Code-Behind: MainWindow.xaml.cs
要使綁定工作,需要在窗口的代碼后面設(shè)置DataContext:
public partial class MainWindow : Window
{public MainWindow(){InitializeComponent();DataContext = new PersonViewModel();}
}