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 someTemp开发者_开发技巧late} />
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.
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;
}
}
Using a TemplateSelector seems to be as good as it gets.
精彩评论