从ItemTemplate里面绑定到ItemsControl的DataContext [英] Bind to ItemsControl's DataContext from inside an ItemTemplate
问题描述
< 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屋!