25

我有一个 ItemsControl,它的 ItemTemplate DataTemplate 包含一个按钮。我希望按钮上的命令绑定到 ItemsControl 的 DataContext 上的命令,而不是 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?

4

1 回答 1

45

您正在将绑定的来源设置为ItemsControl自身。因此,您需要取消对DataContext的引用ItemsControl

Command="{Binding DataContext.GameSelectedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"

你怎么会知道的?运行应用程序时查看调试输出窗口。您将看到一条类似“无法解析类型‘ItemsControl’上的属性‘GameSelectedCommand’”的消息。

于 2009-10-02T20:05:17.147 回答