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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现