【问题标题】:WPF ItemsControl - Command on ViewModel not firing from within ItemsControlWPF ItemsControl - ViewModel 上的命令未从 ItemsControl 中触发
【发布时间】:2009-09-11 10:43:55
【问题描述】:

我正在使用 M-V-VM,并且在我的 ViewModel 上有一个名为“EntitySelectedCommand”的命令。

我试图让 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>

【问题讨论】:

    标签: wpf data-binding mvvm itemscontrol


    【解决方案1】:

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

    1. 也从您的子视图模型中公开一个EntitySelectedCommand(即每个Supplier 也将具有此属性)。
    2. 更改您的绑定以使用RelativeSource 联系并使用父ItemsControlDataContext

    【讨论】:

    • 太好了,非常感谢 - 按照你的建议让它与 RelativeSource 一起工作... EntitySelected="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.EntitySelectedCommand }"
    【解决方案2】:

    看看MVVM Toolkit...它有一个可以使用的命令引用的想法!

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

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

    然后你就可以使用

    ...Command="{StaticResource EntitySelectedCommandRef}" ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2018-11-20
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      相关资源
      最近更新 更多