個人的には、MVVMデザインパターンを使用してこのようなことをします
またはオブジェクトのComboBox
コレクションにバインドされますViewModel
Model
だからあなたは持っているだろう
<ComboBox ItemsSource="{Binding SomeCollection}"
SelectedItem="{Binding SelectedViewModel}"
DisplayMemberPath="DisplayName" />
ここSomeCollection
で、はのコレクションであり、object
は選択したアイテムを保持するためのプロパティですViewModel
SelectedViewModel
object
SomeCollection = new ObservableCollection<object>();
SomeCollection.Add(new ViewModelA());
SomeCollection.Add(new ViewModelB());
SomeCollection.Add(new ViewModelC());
SomeCollection.Add(new ViewModelD());
SomeCollection.Add(new ViewModelE());
SelectedViewModel = SomeCollection[0];
SaveCommand
これで、を使用して選択したものにアクセスSelectedViewModel
し、に基づいて適切なタイプにキャストできますtypeof(SelectedViewModel
)
IViewModel
個人的には、の代わりにのような汎用インターフェースを使用し、object
いくつかの汎用プロパティ(などDisplayName
)とメソッドを含めるようにします。機能によっては、独自の保存ロジックを含めることもできるため、saveコマンドでこれを実行できます。
SelectedViewModel.Save();
正しいView/UserControlの表示に関しては、を使用しContentControl
、それをにContent
バインドし、SelectedViewModel
暗黙のデータテンプレートを使用して、各オブジェクトの描画方法をWPFに指示します。
<ContentControl Content="{Binding SelectedViewModel}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type local:ViewModelA}">
<local:UserControlA />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModelB}">
<local:UserControlB />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModelC}">
<local:UserControlC />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModelD}">
<local:UserControlD />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModelE}">
<local:UserControlE />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>