在我基于 MVVM 的 WPF 应用程序中,我有许多不同的 ViewModel 类型,它们动态加载到 ContentControls 或 ContentPresenters 中。因此,我需要明确设置要在 XAML 中使用的 DataTemplate:
<ContentControl Content={Binding SomePropertyOfTypeViewModel} ContentTemplate={StaticResource someTemplate} />
现在我的问题是,someTemplate
即使 ContentControl 未绑定任何内容(即 ViewModel.SomePropertyOfTypeViewModel 为空) ,内容控件仍在显示 UI 当我使用隐式 DataTemplates 时,一切都按预期工作。不幸的是,我不能在这里使用这种机制。
更新:
我当前的解决方案是bool Visible
为每个 ViewModel 提供一个额外的属性,该属性在父 ViewModel 中作为属性公开。true
仅当属性不为空时才返回。ContentControl 的 Visiblibilty 绑定到此属性。
ParentViewModel.SomePropertyOfTypeViewModelVisible, ParentViewModel.SomeOtherPropertyOfTypeViewModelVisible ...
<ContentControl Content={Binding SomePropertyOfTypeViewModel} Visibility={Binding SomePropertyOfTypeViewModelVisible, Converter={StaticRresource boolToVisibiltyConverter}}" />
这不是很令人满意,因为我必须维护很多额外的属性。