Binding multiple ViewModels to Content Control on

2019-08-31 15:42发布

I have gone through the example of the Tab Control to hold multiple views. But my requirement is bit different.

The content control should be the only region to show the views and it must change according to the Commands for example: Add New, View All, Search, etc..

Thanks in advance.

标签: wpf mvvm
2条回答
相关推荐>>
2楼-- · 2019-08-31 16:11

On your ViewModel you want to have a property:

private object content;
public object Content
{
  get { return content; }
  set
  {
     this.content = value;
     OnPropertyChanged("Content");
  }
}

Then in your main window (or where your content is to be hosted) add a ContentControl:

<ContentControl Content="{Binding Path=Content}"
                HorizontalContentAlignment="Left"
                VerticalContentAlignment="Center"
                Focusable="False"/>

The main ViewModel would maintain a list of known ViewModels (View All, Search) and set the Content property to one of these ViewModels in the appropriate command execution, the Add New command would probably create a new instance of the AddNewViewModel and set the Content property.

In the View where the ContentControl is located put some data templates in the Resources mapping the ViewModels to the appropriate views:

<DataTemplate DataType="{x:Type vm:AddNewViewModel}">
  <AdornerDecorator>
    <views:AddNewView DataContext="{Binding}"/>
  </AdornerDecorator>
</DataTemplate>

This is the basic pattern I am using in a Wizard that I am working on at the moment.

查看更多
Ridiculous、
3楼-- · 2019-08-31 16:21

I used an ObservableCollection<ViewModelBase>. Then on each command (AddNew, ViewAll, etc..) I Added the ViewModel to the collection. But I cleared the collection before I add to it.

查看更多
登录 后发表回答