WPF MVVM 学习理解

<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     }
复制代码

 

posted @   无处不在-超超  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示