0

I know this to be simple, but I can't get it right. This goes to understanding DataBinding in an ItemsControl.

I have an ItemsControl within a ScrollViewer. The ItemsControl will be used to change sub views that are stored in the OvservableCollection Settings.

The Settings and the CurrentViewModel are all in the ViewModel of the main window. From the main view model, I would like to change what is displayed by changing the CurrentViewModel.

If I put the ObservableCollection, Settings, as the ItemsControl Source, then it works to iterate through each item of the collection -- not what I need. So how is this done correctly?

I know I will get kicked with the answer, but please advise. I have not been able to solve this after several hours of Google. (I hope my question is clear). Thanks in advance.

 private SettingsViewModelBase currentViewModel; public SettingsViewModelBase CurrentViewModel { get { return currentViewModel; } set { if (currentViewModel == value) return; currentViewModel = value; OnPropertyChanged("CurrentViewModel"); } } private readonly ObservableCollection<SettingsViewModelBase> settings; public ObservableCollection<SettingsViewModelBase> Settings { get { return this.settings; } } <ScrollViewer Grid.Row="2" Name="scrollviewer1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" > <ItemsControl ItemsSource="{Binding ????}" > <ItemsControl.Resources> <DataTemplate DataType="{x:Type vm_1}"> <vm_1_View/> </DataTemplate> <DataTemplate DataType="{x:Type vm_2}"> <vm_2_view/> </DataTemplate> </ItemsControl.Resources> <ItemsControl.ItemTemplate> <DataTemplate> <ContentControl Content="{Binding ?????" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </ScrollViewer> 
2
  • Did you try {Binding Settings}? Because incredibly obvious? Commented Sep 3, 2014 at 20:43
  • @Will yes. Did not work. Commented Sep 3, 2014 at 21:14

1 Answer 1

2

If you just want to display one view at one time, then you can just use a single ContentControl in the main view to data bind to the CurrentViewModel property in the main view model:

<ContentControl Content="{Binding CurrentViewModel" /> 

Then in the main view model, presumably in response to some UI action, you can just change the value of the CurrentViewModel property:

CurrentViewModel = new vm_2(); 

You can put your DataTemplates into the App.xaml Resources section and then they will be available application wide.

Sign up to request clarification or add additional context in comments.

3 Comments

By "single" do you mean do not use an ItemsControl at all?
That's it--don't use an ItemsControl at all.
Yup, you've got it. Now you can hook up different ICommands to some Button or MenuItem Command properties that each set the CurrentViewModel to a different view model and you have yourself an application.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.