【问题标题】:DataTemplate default visibility for ContentControlsContentControls 的 DataTemplate 默认可见性
【发布时间】:2010-05-03 14:56:30
【问题描述】:

在我基于 MVVM 的 WPF 应用程序中,我有许多不同的 ViewModel 类型,它们动态加载到 ContentControls 或 ContentPresenters 中。因此,我需要明确设置要在 XAML 中使用的 DataTemplate:

<ContentControl Content={Binding SomePropertyOfTypeViewModel} ContentTemplate={StaticResource someTemplate} />

现在我的问题是,即使 ContentControl 没有绑定任何内容(即 ViewModel.SomePropertyOfTypeViewModel 为 null),内容控件也显示 someTemplate 的 UI 有没有一种快速简便的方法可以让所有的 ContentControls 如果它们当前没有绑定任何内容,它们什么都不显示?当我使用隐式 DataTemplates 时,一切都按预期工作。不幸的是,我不能在这里使用这种机制。

更新:

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

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

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

【问题讨论】:

    标签: mvvm datatemplate visibility contentcontrol


    【解决方案1】:

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

    <ContentControl Content={Binding SomePropertyOfTypeViewModel} Visibility={Binding ContentControlVisibility} />
    
    public Visibility ContentControlVisibility
        {
            get
            {
                return SomePropertyOfTypeViewModel == null ? Visibility.Collapsed : Visibility.Visible;
            }
        }
    

    【讨论】:

    • 这正是我试图避免的。这样,我将不得不引入大量新的 bool 属性,每个 ViewModel 通过属性公开一个:ParentViewModel.Child1Visiible, ParentViewModel.Child2Visible ... 我希望得到一个更通用的解决方案,每个 ContentControl 也不需要大量额外的 xaml
    【解决方案2】:

    使用 TemplateSelector 似乎是最好的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 2018-05-19
      • 2016-11-22
      • 2010-11-17
      相关资源
      最近更新 更多