2

在我基于 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}}" />

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

4

2 回答 2

0

设置 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;
        }
    }
于 2010-05-03T19:44:53.683 回答
0

使用 TemplateSelector 似乎是最好的。

于 2010-05-21T12:37:20.197 回答