Alan Wayne
Alan Wayne

Reputation: 5394

How to do data binding in an ItemsControl (MVVM)

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>

Upvotes: 0

Views: 1081

Answers (1)

Sheridan
Sheridan

Reputation: 69987

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.

Upvotes: 2

Related Questions