2009-09-11 54 views
6

我正在使用M-V-VM,并在我的ViewModel上有一个名为“EntitySelectedCommand”的命令。WPF ItemsControl - ViewModel上的命令不会从ItemsControl中触发

我试图让一个ItemsControl中的所有项目发射这个命令,但它不工作。

我认为这是因为每个项目'datacontext'是项目绑定到的个别对象,而不是ViewModel?

任何人都可以指出我正确的方向吗?

干杯,

安迪

<ItemsControl ItemsSource="{Binding Path=LinkedSuppliers}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <StackPanel> 
       <Controls:EntityLabel Grid.Column="0" Grid.Row="0" Content="{Binding Name}" CurrentEntity="{Binding }" EntitySelected="{Binding EntitySelectedCommand}" ></Controls:EntityLabel>     
      <StackPanel> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

回答

13

你的怀疑是正确的。你有两个选择:

  1. 暴露你的孩子视图模型的EntitySelectedCommand以及(即每个Supplier将具有这种属性,太)。
  2. 更改您的绑定以使用RelativeSource联系并使用父ItemsControlDataContext
+3

优秀,非常感谢 - 有它的RelativeSource工作如你所说... EntitySelected =“{Binding RelativeSource = {RelativeSource FindAncestor,AncestorType = {x:Type ItemsControl}},Path = DataContext.EntitySelectedCommand}” – 2009-09-11 15:59:08

2

看看MVVM Toolkit ...它有这个想法,你可以使用命令参考!

创建CommandRefrece作为一种资源,然后只用StaticResource标记扩展...

<c:CommandRefrence x:Key="EntitySelectedCommandRef" Command="{Binding EntitySelectedCommand}" /> 

,再后来,你可以使用

...Command="{StaticResource EntitySelectedCommandRef}" ... 
相关问题