笔记1:WPFCommand命令使用
创建BaseCommand实现Icommand接口
public class BaseCommand : ICommand
{
public Action<object> ExecuteAction;
private BaseCommand filterCommand;
public BaseCommand(Action<object> action)
{
ExecuteAction = action;
}
public BaseCommand(BaseCommand filterCommand)
{
this.filterCommand = filterCommand;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
ExecuteAction(parameter);
}
}
创建ViewModel实现INotifyPropertyChanged接口
public class ViewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// UI通知
/// </summary>
/// <param name="PropertyName"></param>
public void OnPropertyChanged([CallerMemberName]string PropertyName="")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
/// <summary>
/// Command Button点击命令
/// </summary>
public BaseCommand But_click
{
get
{
return new BaseCommand(o=> {
//逻辑代码
});
}
}
}
xaml代码
<Grid>
<Button Command="{Binding But_click}" >
点击
</Button>
</Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//将viewmodel绑定为窗体的数据源
this.DataContext = new ViewModel();
}
}
传递参数
ViewModel
public BaseCommand But_click
{
get
{
return new BaseCommand(o=> {
MessageBox.Show(o.GetType().ToString());
});
}
}
xaml,直接传递string类型的参数
<Button Command="{Binding But_click}" CommandParameter="66">
点击
</Button>
效果图
xaml,传递其他控件的相应属性
<Label Name="image_nasme" Content="你找到我了"/>
<Button Command="{Binding But_click}"
CommandParameter="{Binding Path=Content,ElementName=image_nasme}" >
点击
</Button>
ViewModel
public BaseCommand But_click
{
get
{
return new BaseCommand(o=> {
MessageBox.Show(o.GetType().ToString()+"--->"+o.ToString());
});
}
}
xaml,传递控件自己(RelativeSource={x:Static RelativeSource.Self}}表示绑定自己)
<Label Name="image_nasme" Content="你找到我了"/>
<Button Command="{Binding But_click}"
CommandParameter="{Binding Path=Content,ElementName=image_nasme}" >
点击
</Button>
ViewModel
public BaseCommand But_click
{
get
{
return new BaseCommand(o=> {
MessageBox.Show(o.GetType().ToString()+"--->"+((Button)o).Content);
});
}
}