mvvm - ContentControls 的 DataTemplate 默认可见性

标签 mvvm datatemplate visibility contentcontrol

在我基于 MVVM 的 WPF 应用程序中,我有许多不同的 ViewModel 类型,它们动态加载到 ContentControls 或 ContentPresenters 中。因此,我需要明确设置要在 XAML 中使用的 DataTemplate:
<ContentControl Content={Binding SomePropertyOfTypeViewModel} ContentTemplate={StaticResource someTemplate} />
现在我的问题是内容控件正在显示 someTemplate 的 UI即使 ContentControl 未绑定(bind)任何内容(即 ViewModel.SomePropertyOfTypeViewModel 为空)
是否有一种快速简便的方法可以使所有 ContentControls 如果当前未绑定(bind)任何内容,则不显示任何内容?当我使用隐式 DataTemplates 时,一切都按预期工作。不幸的是,我不能在这里使用这种机制。

更新:

我目前的解决方案是多加一个 bool Visible在父 ViewModel 中作为属性公开的每个 ViewModel 的属性。它返回 true仅当属性不为空时。 ContentControl 的 Visiblibilty 绑定(bind)到此属性。ParentViewModel.SomePropertyOfTypeViewModelVisible, ParentViewModel.SomeOtherPropertyOfTypeViewModelVisible ...

<ContentControl Content={Binding SomePropertyOfTypeViewModel} Visibility={Binding SomePropertyOfTypeViewModelVisible, Converter={StaticRresource boolToVisibiltyConverter}}" />

这不是很令人满意,因为我必须维护很多额外的属性。

最佳答案

设置 ContentControl 的“可见性”会解决您的问题吗?如果是这样,在您的 ViewModel 中,您可以为要绑定(bind)的 ContentControl 的 Visibility 创建一个 Visibility 属性。在属性中,您可以检查 SomePropertyOfTypeViewModel 是否为空。设置 SomePropertyOfTypeViewModel 时,您还需要通知 ContentControlVisibility 属性已更改。

<ContentControl Content={Binding SomePropertyOfTypeViewModel} Visibility={Binding ContentControlVisibility} />

public Visibility ContentControlVisibility
    {
        get
        {
            return SomePropertyOfTypeViewModel == null ? Visibility.Collapsed : Visibility.Visible;
        }
    }

关于mvvm - ContentControls 的 DataTemplate 默认可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2758936/

相关文章:

c# - DispatcherTimer 使用 MVVM 更新 TextBlock

c# - 将数据从属性绑定(bind)到文本 block - MVVM Light 和 WPF

wpf - 在 WPF 中创建可点击的图像

.net - 如何知道我的 ViewModel 中的动画何时完成?

WPF TabControl 和 DataTemplates

wpf - <ColumnDefinition Width ="*"/> 在 DataTemplate 中不受尊重

c# - 尝试获取嵌套在数据模板中的按钮后面的代码

javascript - 切换段落的可见性

Android,使部分文本在TextView中不可见

javascript - css/javascript visibility visible/hidden 在 Blackberry 上非常慢