<Window.DataContext>
<local:ViewModel></local:ViewModel>
</Window.DataContext>
<Grid>
<Button HorizontalAlignment="Left" VerticalAlignment="Top" Content="{Binding MyButton}"/>
<!--<Button HorizontalAlignment="Right" VerticalAlignment="Top" x:Name="mychangebutton" Click="mychangebutton_Click" Content="改变"/>-->
<Button HorizontalAlignment="Right" VerticalAlignment="Top" Command="{Binding ChangeBtn}" Content="改变+1"/>
<Button HorizontalAlignment="Right" VerticalAlignment="Bottom" Command="{Binding ChangeBtn2}" Content="改变+2"/>
</Grid>
namespace WpfApp1
{ //更新事件
public abstract class Notify : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = null) //手动引发更改
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
//按钮事件
public class ActionCommand : ICommand
{
private readonly Action action;
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
action?.Invoke();
}
public ActionCommand(Action _action)
{
action = _action;
}
}
public class ViewModel:Notify
{
public ViewModel()
{
ChangeBtn = new ActionCommand(OnChangeButtonClick); //实例化右侧按钮
ChangeBtn2 = new ActionCommand(OnChangeButtonClick2); //实例化右下侧按钮
}
private void OnChangeButtonClick() //实例化右侧按钮事件
{
this.MyButton += "1";
}
private void OnChangeButtonClick2() //实例化右下侧按钮事件
{
this.MyButton += "2";
}
//实例化左侧显示按钮
private string _myButton="显示按钮A";
public string MyButton
{
get { return _myButton; }
set { _myButton = value;
OnPropertyChanged(); //数据更改
}
}
//右侧按钮
private ICommand _changeBtn;
public ICommand ChangeBtn //按钮中 Command="{Binding ChangeBtn
{
get { return _changeBtn; }
set
{
_changeBtn = value;
OnPropertyChanged();
}
}
//右侧按钮
private ICommand _changeBtn2;
public ICommand ChangeBtn2 //按钮中 Command="{Binding ChangeBtn
{
get { return _changeBtn2; }
set
{
_changeBtn2 = value;
OnPropertyChanged();
}
}
}
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
//private void mychangebutton_Click(object sender, RoutedEventArgs e)
//{
// var myDC = this.DataContext as ViewModel;
// myDC.MyButton += "1";
//}
}
}