I am writing an application using the MVVM pattern. I am providing data to my view by setting my view\'s DataContext property to an instance of my ViewModel. Generally I j
I just tried this tonight:
public class State
{
public string Code { get; set; }
public string Name { get; set; }
}
public class MyWindowViewModel
{
ObservableCollection<State> _states = new ObservableCollection<State>
{
new State { Code = "FL", Name = "Florida" },
new State { Code = "CA", Name = "California" },
};
public ObservableCollection<State> States
{
get
{
return _states;
}
}
}
<Window x:Class="WpfApplication1.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:WpfApplication1"
Title="Window1"
Height="300"
Width="300">
<Window.Resources>
<app:ServiceLocator x:Key="Locator" />
</Window.Resources>
<StackPanel>
<ComboBox x:Name="TestCombo" SelectedIndex="0" DisplayMemberPath="Name" SelectedValuePath="Code">
<ComboBox.ItemsSource>
<CompositeCollection>
<app:State Code="" Name="Select a state..." />
<app:State Code="TX" Name="Texas" />
<CollectionContainer Collection="{Binding Source={StaticResource Locator}, Path=MyWindowViewModel.States}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
</StackPanel>
</Window>
The key here is to create an instance of your service locator as a static resource then go through it to get to your viewmodel. The service locator can wire up to instances of the ViewModel using Unity or whatever DI you want.
Edit:
Actually in my silverlight app I create the service locator as a static resoure in the App.xaml and then bind my other UserControls/Windows/Pages DataContext to a ViewModel property of the service locator. It should still work the same way for the combo boxes though even if the service locator is instantiated in the App.xaml's resources. I wish there was a silverlight version of CompositeCollection that I could use. This would work great for the app I'm working on. :(