正确设置RelativeSource
我在 xaml 表单(主窗口)上有一个组合框。
我在后面的代码中将 Items 源设置为 ObservableCollection。为了填充组合框,我使用了相对源(它位于 ItemsControl 内部),效果很好(没有它,如果没有填充):
ItemsSource="{Binding SelectableItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
我现在已将 ObservableCollection 分解为一个单独的视图模型类,名为“MainWindowViewModel”,组合框不填充。
我已将 MainWindow 的 DataContext 设置为我的 ViewModel,并检查它是否按预期填充其他控件,确实如此。
我应该如何构造RelativeSource以便填充组合框?
谢谢
乔
I have a combo box on a xaml form (MainWindow).
I set the Items source to an ObservableCollection in the code behind. To populate the Combo box I used Relative Source (it sits inside an ItemsControl), which worked great (without it, if did not populate):
ItemsSource="{Binding SelectableItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
I have now factored out the ObservableCollection into a seperate View Model Class, named 'MainWindowViewModel', the combo box does not populate.
I have set the DataContext of the MainWindow to my ViewModel and have checked that it populates other controls as expected, which it does.
How should I construct the RelativeSource so the combo box populates?
Thanks
Joe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我需要在末尾添加路径,因此:
I needed to add the Path at the end, thus:
您不想再使用
RelativeSource
。如果您未指定RelativeSource
(或Source
或ElementName
),则绑定将根据当前DataContext< 进行解析/代码>。由于
DataContext
是继承的,因此您的ItemsControl
从父Window
获取其DataContext
。因此,此绑定将针对您的视图模型进行解析。You do not want to use a
RelativeSource
any longer. If you don't specify aRelativeSource
(orSource
, orElementName
), then the binding will resolve against the currentDataContext
. Since theDataContext
is inherited, yourItemsControl
obtains itsDataContext
from the parentWindow
. Thus, this binding will resolve against your view model.