从ItemTemplate内部绑定到ItemsControl的DataContext

27

我有一个ItemsControl,其中ItemTemplate DataTemplate包含一个按钮。我希望按钮上的Command绑定到ItemsControl的DataContext上的Command,而不是ItemTemplate上的Command。我认为解决方案涉及使用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>

我该如何让按钮绑定到ItemsControl的DataContext对象的GameSelectedCommand命令?

1个回答

46

您正在将绑定的源设置为ItemsControl本身。因此,您需要取消引用ItemsControlDataContext

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

你怎么能知道这个呢? 当应用程序运行时,请查看调试输出窗口。您会看到类似于“Cannot resolve property 'GameSelectedCommand' on type 'ItemsControl'”的消息。


1
谢谢您的回答,但我实际上已经尝试过了。我遇到了以下DataBinding错误: System.Windows.Data Error: 39 : BindingExpression path error: 'DataContext' property not found on 'object' ''RelativeSource' (HashCode=50668565)'. BindingExpression:Path=DataContext.GameSelectedCommand; DataItem='RelativeSource' (HashCode=50668565); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')我不确定它是否真的找到了ItemsControl本身。 - Mark Heath
3
哈!抱歉,我没有注意到你使用的是Source="..."而不是RelativeSource="..."。请查看我的更新答案。 - Kent Boogaart
1
谷歌搜索的SO解决方案是最好的解决方案。 - Erik Kerber
1
啊!每次我总是成功地忘记了这个! - Simon_Weaver
不要忘记在绑定路径中明确加上DataContext.。我以前也经常犯这个错误 :) - Simon_Weaver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接