![](/img/trans.png)
[英]WPF button command in view not firing to ICommand in viewmodel
[英]WPF Button Command not firing ICommand in ViewModel
我有一个带有按钮的视图,如下所示:
<Button Grid.Column="2" Grid.Row="1" Content="Test" Margin="10,4"
Command="{Binding DataContext.CmdTestButtonClicked}"
CommandParameter="{Binding}" />
在视图的代码隐藏中,我将 DataContext 设置为 ViewModel:
public GlobalSettings()
{
InitializeComponent();
...
DataContext = Helpers.IoCHelper.GlobalSettingsVM;
...
}
我的 ViewModel 派生自暴露ICommand
的基类:
public class GlobalSettingsVM : CollectionViewModel<GlobalSettings> { ... }
public abstract class CollectionViewModel<TModel> : IInstallModuleViewModel, INotifyPropertyChanged,
INotifyDataErrorInfo where TModel : Model, new()
{
...
public ICommand CmdTestButtonClicked
{
get
{
return _testButtonClicked ??
(_testButtonClicked = new RelayCommand(TestButtonClicked));
}
}
protected virtual void TestButtonClicked(object o)
{
// I never get here
}
}
我在整个应用程序中使用此模式没有任何其他问题,但是我的所有其他实现在ListView
中都有Button
,因此我必须使用RelativeSource={RelativeSource AncestorType={x:Type ListView}}
。
为什么这个命令永远不会触发? 我还需要在这里设置一个RelativeSource
吗?
这个
Command="{Binding DataContext.CmdTestButtonClicked}"
暗示 Command 将在按钮绑定到的对象中查找名为DataContext
的属性。 如果按钮的 DataContext 是GlobalSettingsVM
这应该可以工作:
Command="{Binding CmdTestButtonClicked}"
您还可以使用 MVVM Light 工具包,它非常方便并有助于解决这些情况。
你会得到这样的东西:
<Button Grid.Column="2" Grid.Row="1" Content="Test" Margin="10,4"
<i:Interaction.Triggers>
<i:EventTrigger EventName="OnClick" >
<Command:EventToCommand Command="{Binding DataContext.CmdTestButtonClicked}" CommandParameter="{Binding}" PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
就我而言,我正在xaml.cs
类的构造函数下收听PreviewMouseLeftButtonDown
,该类正在停止对view model
的command event callback
。
this.PreviewMouseLeftButtonDown += (s, e) => DragMove();
而不是上面的行,在window
的 xaml 文件中添加了MouseLeftButtonDown="Window_MouseLeftButtonDown"
单击处理程序并在其中处理窗口拖动,如下所示
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DragMove();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.