0

いくつかの UserControls の 1 つを表示するウィンドウの一部があります。各 UserControl は、形式、配置、およびスタイルが異なるだけで、同じデータを表示します。Window のこのセクションに表示される特定の UserControl は、Window の ViewModel に格納されている単一の設定によって決定される必要があります。

プログラムのエンド ユーザーが実行時にウィンドウに表示される UserControl を変更できるようにするにはどうすればよいですか?

4

2 に答える 2

0

私はそれを考え出した。私の ViewModel には、 というUserControlプロパティとSelectedUC、 という別のプロパティStyleがあります。これは、使用しenumているさまざまなものを列挙するタイプUserControlsです。私が持っているプロパティのset一部には、のフィールドを対応するタイプの新しいインスタンスに設定し、ViewModel ( ) をパラメーターとして渡すswitch-case ステートメントがあります。StyleOnPropertyChanged("SelectedUC");getSelectedUCSelectedUCUserControlthis

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すべてバインドされ、と を使用する のグループがあります。StyleConverterConverterParameter

<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;
    }
}
于 2013-01-04T13:49:44.287 に答える
0

1 つの (迅速ではあるが必ずしも最善ではない) 方法は、ウィンドウに ContentControl を追加することです。

<ContentControl Name="cc" />

あとは、好きなように内容を設定してください。例えば。コードビハインドで設定する

cc.Content = new UserControl1();
于 2013-01-02T04:41:53.973 に答える