代码之家  ›  专栏  ›  技术社区  ›  Mark Heath

从itemTemplate内部绑定到itemsControl的DataContext

  •  23
  • Mark Heath  · 技术社区  · 15 年前

    我有一个itemsControl,它的itemTemplate数据模板包含一个按钮。我希望按钮上的命令绑定到itemscontrol的dataContext上的命令,而不是itemstemplate。我认为解决方案与使用相对资源有关,但迄今为止我的尝试都失败了:

    <ItemsControl ItemsSource="{Binding Games}">        
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Command="{Binding Path=GameSelectedCommand, Source={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" 
                        CommandParameter="{Binding}" 
                        Style="{StaticResource MenuButtonStyle}" 
                        Content="{Binding Name}"/>    
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    如何获取绑定到ItemsControl的DataContext对象的GameSelectedCommand的按钮?

    1 回复  |  直到 13 年前
        1
  •  43
  •   Tim Cooper    13 年前

    您正在将绑定的源设置为 ItemsControl 本身。因此,您需要取消引用 DataContext 项目控制 :

    Command="{Binding DataContext.GameSelectedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"
    

    你怎么知道的?运行应用程序时,请查看调试输出窗口。在“itemscontrol”类型的“cannot resolve property”gamesselectedcommand“中,您将看到一条消息。