从ItemTemplate里面绑定到ItemsControl的DataContext [英] Bind to ItemsControl's DataContext from inside an ItemTemplate

查看:193
本文介绍了从ItemTemplate里面绑定到ItemsControl的DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ItemsControl,它的ItemTemplate DataTemplate包含一个Button。我希望按钮上的Command绑定到ItemsControl的DataContext上的Command,而不是ItemTemplate。我认为该解决方案与使用RelativeSource有关,但我迄今为止的尝试失败了:

 < ItemsControl ItemsSource ={绑定游戏}> 
< 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>

如何让Button绑定到ItemsControl的DataContext对象的GameSelectedCommand?

解决方案

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

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

你怎么知道这个?运行应用程序时,请查看调试输出窗口。您会在ItemsControl类型的无法解析属性GameSelectedCommand上看到一条消息。


I have an ItemsControl whose for the ItemTemplate DataTemplate contains a Button. I want the Command on the button to bind to a Command on the DataContext of the ItemsControl, not the ItemTemplate. I think the solution has to do with using RelativeSource, but my attempts so far have failed:

<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>

How can I get the Button to bind to the GameSelectedCommand of the ItemsControl's DataContext object?

解决方案

You're setting the source of the binding to the ItemsControl itself. Therefore, you'll need to dereference the DataContext of the ItemsControl:

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

How would you have known this? Take a look at your debug output window when running the app. You'll see a message along the lines of "Cannot resolve property 'GameSelectedCommand' on type 'ItemsControl'".

这篇关于从ItemTemplate里面绑定到ItemsControl的DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆