从ItemTemplate内部绑定到ItemsControl的DataContext

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自身.因此,你需要取消引用DataContextItemsControl:

Command="{Binding DataContext.GameSelectedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"
Run Code Online (Sandbox Code Playgroud)

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

  • 哈!对不起,我错过了你有Source ="..."而不是RelativeSource ="..."的事实.看到我更新的答案. (3认同)