Why is CompositeCollection not Freezable?

前端 未结 1 693
悲哀的现实
悲哀的现实 2020-12-03 13:39

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

相关标签:
1条回答
  • 2020-12-03 14:17

    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. :(

    0 讨论(0)
提交回复
热议问题