いくつかの UserControls の 1 つを表示するウィンドウの一部があります。各 UserControl は、形式、配置、およびスタイルが異なるだけで、同じデータを表示します。Window のこのセクションに表示される特定の UserControl は、Window の ViewModel に格納されている単一の設定によって決定される必要があります。
プログラムのエンド ユーザーが実行時にウィンドウに表示される UserControl を変更できるようにするにはどうすればよいですか?
いくつかの UserControls の 1 つを表示するウィンドウの一部があります。各 UserControl は、形式、配置、およびスタイルが異なるだけで、同じデータを表示します。Window のこのセクションに表示される特定の UserControl は、Window の ViewModel に格納されている単一の設定によって決定される必要があります。
プログラムのエンド ユーザーが実行時にウィンドウに表示される UserControl を変更できるようにするにはどうすればよいですか?
私はそれを考え出した。私の ViewModel には、 というUserControl
プロパティとSelectedUC
、 という別のプロパティStyle
があります。これは、使用しenum
ているさまざまなものを列挙するタイプUserControls
です。私が持っているプロパティのset
一部には、のフィールドを対応するタイプの新しいインスタンスに設定し、ViewModel ( ) をパラメーターとして渡すswitch-case ステートメントがあります。Style
OnPropertyChanged("SelectedUC");
get
SelectedUC
SelectedUC
UserControl
this
private MyStyleEnum _style = MyStyleEnum.OneStyle;
public MyStyleEnum Style
{
get { return _style; }
set
{
if (value != _style)
{
_style = value;
OnPropertyChanged("Style");
OnPropertyChanged("SelectedUC");
}
}
}
private UserControl _selectedUC;
public UserControl SelectedUC
{
get
{
switch (Style)
{
case MyStyleEnum.OneStyle:
_selectedUC = new ucOneControl(this);
break;
case MyStyleEnum.AnotherStyle:
_selectedUC = new ucAnotherControl(this);
break;
}
return _selectedUC;
}
set { _selectedUC = value; }
}
私MainView
のxamlには、ViewModelのプロパティにContentPresenter
バインドContent
されたプロパティがあります。SelectedUC
<ContentPresenter Content="{Binding SelectedUC}" />
私SettingsView
の の xaml には、プロパティにRadioButton
すべてバインドされ、と を使用する のグループがあります。Style
Converter
ConverterParameter
<Window x:Class="MyProject.View.SettingsView"
xmlns:cv="clr-namespace:MyProject.Converters"
xmlns:vm="clr-namespace:MyProject.ViewModel">
<Window.Resources>
<cv:EnumToBoolConverter x:Key="EBConverter"/>
</Window.Resources>
<RadioButton Content="One" IsChecked="{Binding Path=Style, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ResourceKey=EBConverter}, ConverterParameter={x:Static Member=vm:MyStyleEnum.SingleLine}}"/>
</Window>
EnumToBoolConverter.cs:
public class EnumToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (parameter.Equals(value))
return true;
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return parameter;
}
}
1 つの (迅速ではあるが必ずしも最善ではない) 方法は、ウィンドウに ContentControl を追加することです。
<ContentControl Name="cc" />
あとは、好きなように内容を設定してください。例えば。コードビハインドで設定する
cc.Content = new UserControl1();