按钮更新文本框需要通知事件
<Grid>
<StackPanel>
<TextBlock Text="{Binding Name}"></TextBlock>
<Button Content="Show" Command="{Binding ShowCommand}"></Button>
</StackPanel>
</Grid>
using System;
using System.Windows.Input;
namespace wpf命令
{
public class MyCommand : ICommand
{
Action executeAction;
public MyCommand(Action action)
{
executeAction = action;
}
//命令状态改变触发
public event EventHandler? CanExecuteChanged;
//能不能执行动作
public bool CanExecute(object? parameter)
{
return true;
}
//执行动作具体代码
public void Execute (object? parameter)
{
executeAction();
}
}
}
using System.ComponentModel;
//using System.Runtime.CompilerServices;
using System.Windows;
namespace wpf命令
{
public class MainViewModel: INotifyPropertyChanged
{
//绑定ui
public MyCommand ShowCommand { get; set; }
private string name;
//这种写法比较重
public string Name
{
get
{
return name;
}
set
{
name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
public MainViewModel()
{
ShowCommand = new MyCommand(Show);
Name = "Hello";
}
public event PropertyChangedEventHandler PropertyChanged;
//UI分离
//跟按钮建立关系
public void Show()
{
Name = "我点击了按钮";
MessageBox.Show(Name);
}
}
}
namespace wpf命令
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//上下文
this.DataContext = new MainViewModel();
}
}
}
增加一项需要加很多代码
改进
把通知事件单独写道一个类
using System.ComponentModel;
namespace wpf命令
{
public class ViewModeBase: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
//属性通知更改propertyName属性
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke (this, new PropertyChangedEventArgs(propertyName));
}
}
}
using System.ComponentModel;
//using System.Runtime.CompilerServices;
using System.Windows;
namespace wpf命令
{
public class MainViewModel: ViewModeBase
{
//绑定ui
public MyCommand ShowCommand { get; set; }
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
OnPropertyChanged("Name");
}
}
public string title;
public string Title
{
get { return title; }
set { title = value; OnPropertyChanged("Title"); }
}
public MainViewModel()
{
ShowCommand = new MyCommand(Show);
Name = "Hello";
}
//UI分离
//跟按钮建立关系
public void Show()
{
Name = "我点击了按钮";
MessageBox.Show(Name);
}
}
}
在改进自动识别传参
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace wpf命令
{
public class ViewModeBase: INotifyPropertyChanged
{
//没有显示订阅该事件
//内部实现通知更改
public event PropertyChangedEventHandler PropertyChanged;
//属性通知更改propertyName属性
//特性[CallerMemberName] 调用默认属性
public void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
//按照约定规则Invoke
PropertyChanged?.Invoke (this, new PropertyChangedEventArgs(propertyName));
}
}
}