David
David

Reputation: 13

It is possible to bind collection of different viewmodels in some viewcollection (c# XAML WPF)?

XAML:

<ItemsControl ItemsSource="{Binding Messages}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Views:Message110FirstView DataContext="{Binding}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

VIEWMODEL:

public ObservableCollection<ViewModelBase> Messages
    {
        get { return GetValue<ObservableCollection<ViewModelBase>>(MessagesProperty); }
        set { SetValue(MessagesProperty, value); }
    }
    public static readonly PropertyData MessagesProperty = RegisterProperty("Messages", typeof(ObservableCollection<ViewModelBase>), null);

My question relates to this part of xaml:

<Views:Message110FirstView DataContext="{Binding}"/>

So, how to make different views in this place.

Thank you.

Upvotes: 0

Views: 78

Answers (1)

StepUp
StepUp

Reputation: 38199

If I understand you correctly, then you want change view based in viewmodel.

It is appropriate to use DataTemplates if you want to dynamically switch Views depending on the ViewModel:

<Window>
   <Window.Resources>
      <DataTemplate DataType="{x:Type ViewModelA}">
         <localControls:ViewAUserControl/>
      </DataTemplate>
      <DataTemplate DataType="{x:Type ViewModelB}">
         <localControls:ViewBUserControl/>
      </DataTemplate>
   <Window.Resources>
  <ContentPresenter Content="{Binding CurrentView}"/>
</Window>

If Window.DataContext is an instance of ViewModelA, then ViewA will be displayed and Window.DataContext is an instance of ViewModelB, then ViewB will be displayed.

The best example I've ever seen and read it is made by Rachel Lim. See the example.

Upvotes: 1

Related Questions