我有一个Windows应用商店,遵循MVVM模式。 我有一个包含GridView控件的父视图(具有匹配的Parent ViewModel)。 该GridView控件的ItemTemplate包含一个子视图。 该子视图包含几个按钮。在WinRT中暴露GridView中MVVM用户控件的命令
如何连接它,以便当用户单击其中一个ChildView控件上的按钮时,父视图模型上会调用一个方法?
我有一个Windows应用商店,遵循MVVM模式。 我有一个包含GridView控件的父视图(具有匹配的Parent ViewModel)。 该GridView控件的ItemTemplate包含一个子视图。 该子视图包含几个按钮。在WinRT中暴露GridView中MVVM用户控件的命令
如何连接它,以便当用户单击其中一个ChildView控件上的按钮时,父视图模型上会调用一个方法?
这就是我解决这个问题的方法。
在后面的子视图代码上添加一个ICommand支持的依赖属性。
public static readonly DependencyProperty ChildButtonCommandProperty = DependencyProperty.Register("ChildButtonCommand", typeof(ICommand), typeof(ChildView),new PropertyMetadata(null, OnChildButtonCommandChanged));
public ICommand ChildButtonCommand
{
get { return (ICommand)GetValue(ChildButtonCommandProperty); }
set { SetValue(ChildButtonCommandProperty, value); }
}
private static void OnChildButtonCommandChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var self = (ChildView)sender;
self.ChildButtonCommand.Command = (ICommand)e.NewValue;
}
在父视图模型,添加型的ICommand一个公共的getter属性,具有RelayCommand,你可以在这里找到实现:https://relaycommandrt.codeplex.com/
父视图的XAML中,绑定ChildButtonCommand在子视图:
<GridView.ItemTemplate>
<DataTemplate>
<views:ChildView ChildButtonCommand="{Binding ElementName=ParentView, Path=DataContext.PropertyOnParentViewModel}"/>
</DataTemplate>
仔细检查绑定语法。由于我们在GridView项目的DataTemplate中,我们的DataContext是而不是父视图模型(它是子项目对象)。如果我们想将按钮命令绑定到父视图模型,我们需要在父视图中引用某些东西。在这种情况下,我将视图命名为“ParentView”。使用Binding ElementName语法,我可以绑定到ParentView的DataContext,更具体地说是ParentViewModel上的一个属性。
有两种方法可以做到这一点。
感谢您的帮助。使用您建议的第一种方法,您是否暗示子视图对父视图模型有依赖关系? –