【问题标题】:Bind to ItemsControl's DataContext from inside an ItemTemplate从 ItemTemplate 中绑定到 ItemsControl 的 DataContext
【发布时间】:2010-12-03 10:45:39
【问题描述】:

我有一个 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?

【问题讨论】:

    标签: wpf data-binding xaml datatemplate itemscontrol


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您的回答,但我确实尝试过这个。我收到以下 DataBinding 错误:System.Windows.Data 错误:39:BindingExpression 路径错误:在“对象”“RelativeSource”(HashCode=50668565)上找不到“DataContext”属性。 BindingExpression:Path=DataContext.GameSelectedCommand; DataItem='RelativeSource' (HashCode=50668565);目标元素是 'Button' (Name='');目标属性是“命令”(类型“ICommand”)我不确定它是否真的找到了 ItemsControl 本身
    • 哈!抱歉,我错过了您使用 Source=".​​.." 而不是 RelativeSource=".​​.." 的事实。请参阅我的更新答案。
    • 谷歌搜索的 SO 解决方案是最好的解决方案。
    • 啊!我每次都能成功地忘记这一点!
    • 不要忘记将DataContext. 明确放入绑定路径中。以前也经常犯这个错误:)
    猜你喜欢
    • 2014-07-30
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 2011-12-04
    • 2011-03-27
    • 2012-01-19
    • 2012-02-17
    相关资源
    最近更新 更多