views:

66

answers:

2

In my MVVM based WPF application I have a lot of different ViewModel types that dynamically loaded into ContentControls or ContentPresenters. Therefor I need to explictly set what DataTemplate is to be used in XAML:

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

Now my problem is that the content control is displaying the UI of someTemplate even if the ContentControl is bound to nothing (i.e ViewModel.SomePropertyOfTypeViewModel is null) Is there a quick and easy way to make all ContentControls display nothing if they are currently bound to nothing? When I use implicit DataTemplates everything works as expected. Unfortunately I can't use this mechanism here.

Update:

My current solution is to have one extra bool Visible property for each ViewModel that is exposed as a property in the parent ViewModels. It returns true only when the the property is not null. The ContentControl's Visiblibilty is bound to this property. ParentViewModel.SomePropertyOfTypeViewModelVisible, ParentViewModel.SomeOtherPropertyOfTypeViewModelVisible ...

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

This is not very satisfying because I have to maintain a lot of extra properties.

A: 

Would setting the 'Visibility' of the ContentControl solve your problem? If so, in your ViewModel, you could create a Visibility property for the Visibility of the ContentControl to bind to. In the property, you could check to see if SomePropertyOfTypeViewModel is null. When setting the SomePropertyOfTypeViewModel, you would also want to notify that the ContentControlVisibility property changed.

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

public Visibility ContentControlVisibility
    {
        get
        {
            return SomePropertyOfTypeViewModel == null ? Visibility.Collapsed : Visibility.Visible;
        }
    }
JSprang
This is exactly what I was trying to avoid. This way I would have to introduce tons of new bool properties, one for each ViewModel that is exposed via a property: `ParentViewModel.Child1Visiible, ParentViewModel.Child2Visible ...` I was hoping to get a more generic solution that also would not require a lot of extra xaml for each ContentControl
bitbonk
A: 

Using a TemplateSelector seems to be as good as it gets.

bitbonk