我正在尝试在包含两个集合 A 和 B 的 ViewModel 上绑定(bind)一个 WPF 窗口。我正在尝试使用 DataTemplates 根据我的 ViewModel 中的标志设置来显示 A 或 B。
为此,我设置了窗口的 DataContext = ViewModel
.但是,当我尝试绑定(bind) ContentControl
到那个 DataContext 并应用 DataTemplateSelector
对它来说,item
选择器的参数SelectTemplate(object item, DependencyObject container)
方法始终为空:
<Window [snip] Title="MainWindow">
<Window.Resources>
<!-- DataTemplate and Selector declarations -->
</Window.Resources>
<Grid>
<ContentControl Content="{Binding}"
ContentTemplateSelector="{StaticResource templateSelector}" />
</Grid>
</Window>
我应该如何绑定(bind)
ContentControl
这样 Window 的 ViewModel 将被传递到它的 DataTemplateSelector
?
最佳答案
这对我有用:
<ContentControl Content="{Binding DataContext, RelativeSource={RelativeSource Self}}"
ContentTemplateSelector="{StaticResource templateSelector}" />
编辑:
不过,我同意 Aaron 的观点,这可能不是完成事情的最佳方式。您说您正在使用 ViewModel。最简单的方法可能是将您的 ItemsControl 绑定(bind)到 Viewmodel 上的新“SelectedCollection”属性,该属性公开所需的集合。然后在您的标志中(假设它是一个属性),您可以为“SelectedCollection”触发 propertychanged。
关于wpf - 如何将 WPF 控件的内容绑定(bind)到其容器的 DataContext,以便可以基于该对象应用 DataTemplateSelector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5036835/