Paul
Paul

Reputation: 970

How to set datacontext for each combobox?

I'm having a problem about binding in combobox ( WPF, MVVM). I have a combobox, which binds to AViewModel ( for example). To do that, I did have: - AModel - AViewModel - Xaml file :

<Window.DataContext>
    <ViewModel:AViewModel/>
</Window.DataContext>

It works fine.

But, now, I add one more combobox to the same form with combobox above. This combobox binds to diffirent ViewModel (BViewMoel for example, note that, this BViewModel located in diffirent file with AViewModel above). And this is combobox xaml:

<ComboBox 
    DataContext="BViewModel" 
    ItemsSource="{Binding Path=MyList}" DisplayMemberPath="BName"/>

My problem is: the second combobox is not populated because it does not have datacontext. But I cannot set datacontext for it because it is set above for AViewModel.

I did a lots of searching but I still stuck in this. Should I merge all ViewModels into a ViewModel and set this to Datacontext of Window or any ideal? Thank you.

Upvotes: 0

Views: 432

Answers (2)

ken2k
ken2k

Reputation: 48985

Really, I wouldn't use a ViewModel for each combobox. Combobox is a simple control, you should bind the ItemsSource property to a public property (of type ObservableCollection<T> for instance) of the ViewModel of the owner view.

Sometimes it's useful to use a ViewModel for a specific and complex usercontrol. In this case, you can expose the viewModel as a public property of the ViewModel of the owner view:

public class UCViewModel : ViewModelBase
{
}

public class MyViewViewModel : ViewModelBase
{
    public MyViewViewModel()
    {
        this.UCViewModel = new UCViewModel();
    }

    public UCViewModel UCViewModel { get; set; }
}

<Window x:Class="MyView">

    <MyComplexUsercontrol DataContext="{Binding UCViewModel}" />

</Window>

public partial class MyView : Window
{
    public MyView()
    {
        InitializeComponent();
        this.DataContext = new MyViewViewModel();
    }
}

But again, for a simple combobox, just bind it to a property of the ViewModel associated with the owner view.

Upvotes: 4

Jason Li
Jason Li

Reputation: 1585

combobox1.DataContext = new AViewModel();
combobox2.DataContext = new BViewModel();

But I suggest using a ViewModel contains two properties.

public class ViewModel
{
    public AViewModel AViewModel{get;set;}
    public BViewModel BViewModel{get;set;}
}

Upvotes: 2

Related Questions