【问题标题】:Setting RelativeSource correctly正确设置 RelativeSource
【发布时间】:2011-09-12 23:47:00
【问题描述】:

我在 xaml 表单 (MainWindow) 上有一个组合框。

我在后面的代码中将 Items 源设置为 ObservableCollection。为了填充组合框,我使用了相对源(它位于 ItemsControl 内),效果很好(没有它,如果没有填充):

ItemsSource="{Binding SelectableItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"

我现在已将 ObservableCollection 分解为一个单独的视图模型类,名为“MainWindowViewModel”,组合框不会填充。

我已将 MainWindow 的 DataContext 设置为我的 ViewModel 并检查了它是否按预期填充了其他控件,确实如此。

我应该如何构造 RelativeSource 以便填充组合框?

谢谢

【问题讨论】:

  • 我不确定你是否需要RelativeSource,组合框应该从窗口继承它的数据上下文吗?
  • 谢谢 jk - 是的,我也这么认为 - 我认为它没有填充,因为它位于 ItemsControl.Template 中:ItemsSource="{Binding SelectableItems} 没有填充

标签: wpf xaml observablecollection


【解决方案1】:

我需要在最后添加路径,因此:

ItemsSource="{Binding SelectableItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.SelectableItems}"

【讨论】:

  • 尝试只使用Path=SelectableItems
  • 我是一个相对的 WPF 新手,但我试图更好地理解 RelativeSource。在我看来,您已经告诉项目源使用父窗口使用的相同 DataContext 并在该上下文中使用名为 SelectableItems 的属性。由于默认情况下您将继承该 DataContext,因此您未向我们显示的 xaml 父链中的某些内容必须使用不同的数据上下文。我通过阅读您的帖子学习了 Path=DataContext.Property 的正确语法,因此为此 +1。
【解决方案2】:

您不想再使用RelativeSource。如果您未指定RelativeSource(或Source,或ElementName),则绑定将针对当前DataContext 进行解析。由于DataContext 被继承,您的ItemsControl 从父Window 获得其DataContext。因此,此绑定将针对您的视图模型进行解析。

ItemsSource="{Binding SelectableItems}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多