从ItemTemplate内部绑定到ItemsControl的DataContext

时间:2009-10-02 19:59:45

标签: wpf data-binding 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>

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

1 个答案:

答案 0 :(得分:43)

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

ItemsControl

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

相关问题