Mar*_*ath 23 data-binding wpf xaml datatemplate itemscontrol
我有一个ItemsControl,其ItemTemplate DataTemplate包含一个Button.我希望按钮上的Command绑定到ItemsControl的DataContext上的Command,而不是ItemTemplate.我认为解决方案与使用RelativeSource有关,但到目前为止我的尝试都失败了:
<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>
Run Code Online (Sandbox Code Playgroud)
如何让Button绑定到ItemsControl的DataContext对象的GameSelectedCommand?
Ken*_*art 43
您正在设置绑定的源ItemsControl
自身.因此,你需要取消引用DataContext
的ItemsControl
:
Command="{Binding DataContext.GameSelectedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"
Run Code Online (Sandbox Code Playgroud)
你怎么会知道这个?运行应用程序时,请查看调试输出窗口.您将在类型'ItemsControl'上看到"无法解析属性'GameSelectedCommand'的消息."