2013-07-03 43 views
1

我有一个Windows应用商店,遵循MVVM模式。 我有一个包含GridView控件的父视图(具有匹配的Parent ViewModel)。 该GridView控件的ItemTemplate包含一个子视图。 该子视图包含几个按钮。在WinRT中暴露GridView中MVVM用户控件的命令

如何连接它,以便当用户单击其中一个ChildView控件上的按钮时,父视图模型上会调用一个方法?

回答

0

这就是我解决这个问题的方法。

  1. 在后面的子视图代码上添加一个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; 
    } 
    
  2. 在父视图模型,添加型的ICommand一个公共的getter属性,具有RelayCommand,你可以在这里找到实现:https://relaycommandrt.codeplex.com/

  3. 父视图的XAML中,绑定ChildButtonCommand在子视图:

    <GridView.ItemTemplate> 
    <DataTemplate> 
        <views:ChildView ChildButtonCommand="{Binding ElementName=ParentView, Path=DataContext.PropertyOnParentViewModel}"/> 
    </DataTemplate> 
    

仔细检查绑定语法。由于我们在GridView项目的DataTemplate中,我们的DataContext是而不是父视图模型(它是子项目对象)。如果我们想将按钮命令绑定到父视图模型,我们需要在父视图中引用某些东西。在这种情况下,我将视图命名为“ParentView”。使用Binding ElementName语法,我可以绑定到ParentView的DataContext,更具体地说是ParentViewModel上的一个属性。

1

有两种方法可以做到这一点。

  • 您可以使用的第一个方法是 - 将您的按钮绑定到您的父视图模型中定义的命令,您可以在其中进行工作。
  • 第二个是 - 你可以使用mvvm messenger类。在其中您必须将消息从您的按钮单击事件处理程序发送到您的视图模型。当您收到此消息时,请添加一些事件处理程序并在其中执行您的工作。
+0

感谢您的帮助。使用您建议的第一种方法,您是否暗示子视图对父视图模型有依赖关系? –