问题
I'm creating a WPF application, which has a main screen in which other screens are loaded.
The main screen can be seen as a header/footer template where the central part is replaced depending on what I need to show at that moment. (It's a 3 row grid where the usercontrol
should be put in row 1). This has a viewmodel
that is changing header/footer status.
I have implemented those changing parts (row 1) as usercontrols.
Now I am wondering if there is any way to use binding (to something..) so that I can change the loaded usercontrol
and not do it from code behind as I'm doing it now.
If this is going completely against MVVM principles, please give me hints on how I should handle this.
Thanks!!
回答1:
It sounds to me like you should be looking at using WPF's DataTemplates.
Take this example XAML based on your question:
<Grid>
... XAML for your Header and Footer
<ContentPresenter Content="{Binding MainContent">
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type viewmodel:UserControlViewModel}">
<view:UserControlView>
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
</Grid>
Here I'm using a ContentPresenter to act as a placeholder for your content. This is bound to a property called MainContent
on your main viewmodel. In your viewmodel, you could then set the MainContent to be the viewmodel for your usercontrol.
The ContentPresenter
will attempt to display whatever object it is bound to. In this example, I've created a DataTemplate that maps a specific object type (e.g. UserControlViewModel) to a view (e.g. UserControlView).
You can define multiple DataTemplates, to allow your content presenter to handle multiple viewmodels (or any type of object):
<Grid>
... XAML for your Header and Footer
<ContentPresenter Content="{Binding MainContent">
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type viewmodel:UserControlViewModel}">
<view:UserControlView>
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodel:AnotherUserControlViewModel}">
<view:AnotherUserControlView>
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
</Grid>
I hope that points you in the right direction.
You can find out more info on Data Templating on MSDN:
https://msdn.microsoft.com/en-us/library/ms742521(v=vs.110).aspx
EDIT: It's worth mentioning that you COULD just new-up your UserControl.xaml in your main viewmodel, and set that to the MainContent property. No DataTemplate would be required there, as the ContentPresenter knows how to present a UserControl. However, this goes against MVVM, as you're tightly coupling your UI (XAML) with your code (viewmodel).
来源:https://stackoverflow.com/questions/29679847/use-binding-to-change-usercontrol-in-a-grid