WPF MVVM 学习理解

发布时间 2023-11-29 15:05:34作者: 无处不在-超超
<StackPanel>
    <TextBox Text="{Binding Name}"/>
    <TextBox Text="{Binding Title}"/>
    <Button Height="50" Command="{Binding ShowCommand}"/>
</StackPanel>

数据上下文绑定:

this.DataContext = new MainViewModel();

ViewModel:

 1 internal class MainViewModel : ViewModelBase
 2 {
 3     public MainViewModel()
 4     {
 5         ShowCommand = new MyCommond(Show);
 6     }
 7     private string name;
 8     public string Name 
 9     {
10         get { return name; }
11         set 
12         {
13             name = value; 
14             OnPropertyChanged();
15         } 
16     }
17     private string title;
18     public string Title
19     {
20         get { return title; }
21         set
22         {
23             title = value;
24             OnPropertyChanged();
25         }
26     }
27     public MyCommond ShowCommand { get; set; }
28 
29 
30     public void Show()
31     {
32         Name = "按钮";
33         Title = "标题";
34         MessageBox.Show(Name);
35     }
36 
37 }

ViewModelBase:

1 internal class ViewModelBase : INotifyPropertyChanged
2 {
3     public event PropertyChangedEventHandler PropertyChanged;
4     public void OnPropertyChanged([CallerMemberName]string propertyName = "")
5     {
6         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
7     }
8 }

绑定Command:

 1     internal class MyCommond : ICommand
 2     {
 3         Action executeAction;
 4         public MyCommond(Action action) 
 5         {
 6             executeAction = action;
 7         }
 8         public event EventHandler CanExecuteChanged;
 9 
10         public bool CanExecute(object parameter)
11         {
12             return true;
13         }
14 
15         public void Execute(object parameter)
16         {
17             executeAction();
18         }
19     }