<Grid >
<StackPanel>
<TextBox Text="{Binding Name}"/>
<Button Content="Show" Command="{Binding ShowCommand}"/>
</StackPanel>
</Grid>
系统cs文件
public MainWindow()
{
InitializeComponent();
//调用方法
this.DataContext = new MainViewModel();
}
新建文件1
public class MainViewModel
{
public MainViewModel()
{
Name = "Hello";
//show是与xmal绑定。接收一个方法,这个方法因为需要另一个方法作为参数传进来,所以需要用委托
ShowCommand = new MyCommand(Show);
}
public string Name { get; set; }
//与ui建立关系
public MyCommand ShowCommand { get; set; }
//写好了一个方法,需要任何一个ui都可以使用它
public void Show()
{
Name = "点击了按钮!";
MessageBox.Show(Name);
}
}
新建文件2(存放具体业务)
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();
}
}