我有一个带按钮的视图,如下所示:
<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
}
}
我在整个应用程序中没有使用此模式的任何其他问题,但是我的所有其他实现在Button
内都有ListView
,所以我必须使用{{1} }。
为什么这个命令永远不会开火?我是否还需要在此处设置RelativeSource={RelativeSource AncestorType={x:Type ListView}}
?
答案 0 :(得分:1)
这个
Command="{Binding DataContext.CmdTestButtonClicked}"
意味着Command将在按钮绑定的对象中查找名为DataContext
的属性。
如果按钮的DataContext是GlobalSettingsVM
,这应该可以工作:
Command="{Binding CmdTestButtonClicked}"
答案 1 :(得分:0)
您还可以使用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>