开发者

MVVM Silverlight 4 Parent Child View Models

开发者 https://www.devze.com 2023-03-09 07:07 出处:网络
I have a page that holds a number combo boxes. Each combo box is bound to a separate viewmodel. How would I get all the values from the comboboxes and pass them to another viewmodel (using mvvm)?

I have a page that holds a number combo boxes. Each combo box is bound to a separate viewmodel. How would I get all the values from the comboboxes and pass them to another viewmodel (using mvvm)?

I've briefly looked into creating a new viewmodel with properties that are the combobox viewmodels but the binding doesn't seem to work.

Any ideas?

Thanks, Gra开发者_运维百科eme


If I understand you correctly, you should have the parent bind to the SelectedItem of the combobox. My fear is that your SelectedItem is already bound to your ComboBox's view model, but that is generally not a good idea.

ViewModels should be used only privately in a control. So for example, in your combobox, you might want to instead create a new user control that contains that combobox. This way, you can handle all of your 'child' view model stuff in the user control and the consumer of your new user control can bind and interact with any element it chooses without being constrained.


If I understand you conrrectly you have ComboBoxes filled with separated ViewModels (using ItemsSource), so to get values from them you should bind its SelectedItem properties to one ViewModel.

To show you what I mean, lets assume we have 2 ViewModels:

public class ItemOneViewModel
{
 public Name { get; set; }
}

public class ItemTwoViewModel
{
 public Name { get; set; }
}

and one common ViewModel:

public class MainViewModel
{
 public ObservableCollection<ItemOneViewModel> ComboBox1Items { get; set; }
 public ObservableCollection<ItemTwoViewModel> ComboBox2Items { get; set; }

 public ItemOneViewModel SelectedItemFromComboBox1 { get; set; }
 public ItemTwoViewModel SelectedItemFromComboBox2 { get; set; }
}

and then you can bind:

  • ComboBox1Items with ItemsSource of ComboBox1
  • SelectedItemFromComboBox1 with SelectedItem of ComboBox1
  • ComboBox2Items with ItemsSource of ComboBox2
  • SelectedItemFromComboBox2 with SelectedItem of ComboBox2

thanks to it in MainViewModel you have access to selected values in ComboBoxes.

I hope you understand something from my explanation ;)

The code above is simplified version of course - all ViewModels should probably implement INotifyPropertyChanged interface.

0

精彩评论

暂无评论...
验证码 换一张
取 消