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

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

问题描述

我有一个 ItemsControl,它的 ItemTemplate DataTemplate 包含一个按钮.我希望按钮上的命令绑定到 ItemsControl 的 DataContext 上的命令,而不是 ItemTemplate.我认为解决方案与使用 RelativeSource 有关,但到目前为止我的尝试都失败了:

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>

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

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

推荐答案

您正在将绑定源设置为 ItemsControl 本身.因此,您需要取消引用 ItemsControlDataContext:

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

你怎么知道的?运行应用程序时查看您的调试输出窗口.您将看到一条消息,内容为无法解析类型 'ItemsControl' 上的属性 'GameSelectedCommand'".

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天全站免登陆