[英]Bind RelayCommand to Button Click or CodeBehind
我想将RelayCommand绑定到Button Click事件
(我知道我可以绑定到命令属性,但我想绑定到click事件)
我该怎么做?
我使用此代码,但无法正常工作:
private void Button_Clicked(object sender, RoutedEventArgs e) {
FrameworkElement fe=sender as FrameworkElement;
((FirstViewModel)fe.DataContext).ShowSecondViewCommand();
}
我的某些个人控件没有此属性(命令),因此我无法将命令绑定到命令属性
假设您具有正确的xaml来绑定命令。 以下代码将执行分配给按钮的命令:
private void Button_Clicked(object sender, RoutedEventArgs e) {
var button = sender as Button;
if(button.Command != null){
button.Command.Execute(null);
}
}
您需要使用InvokeCommandAction
类或EventToCommand
的InvokeCommandAction
类来执行此操作
<Button xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding Path=SomeCommand, Mode=OneWay}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
坦白说,这不是最佳做法。 您的控件不可能只公开Command属性吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.