1

5つのエントリと5つのUserControlを持つComboBoxを取得しました。

ComboBoxエントリを選択するとき、最初のUserControlをグリッドに割り当てたいと思います。2番目のComboBoxエントリ、2番目のUserControl、3番目のエントリ...など。

これで、各UserControlには、TextControls、ComboBoxes、CheckBoxesなどの一連のコントロールが含まれます。

次の擬似コードを想像してみましょう。

combobox_SelectedIndexChanged()
{
    if(comboBox.SelectedIndex == 1)
       grid.Content = new UserControlOne();
    else if(comboBox.SelectedIndex == 2)
       grid.Content = new UserControlTwo();
    else if(comboBox.SelectedIndex == 3)
       grid.Content = new UserControlThree();
    [...]
}

ボタンクリックで、割り当てられたコントロールの値を取得したいのですが、UserControlにアクセスする方法がわかりません。

buttonSave_click()
{
    //TODO: Get Values of a UserControl and assign it to the Model-Class    
}

UserControlのコントロールにアクセスしてその値を取得するにはどうすればよいですか?

4

2 に答える 2

3

個人的には、MVVMデザインパターンを使用してこのようなことをします

またはオブジェクトのComboBoxコレクションにバインドされますViewModelModel

だからあなたは持っているだろう

<ComboBox ItemsSource="{Binding SomeCollection}" 
          SelectedItem="{Binding SelectedViewModel}"
          DisplayMemberPath="DisplayName" />

ここSomeCollectionで、はのコレクションであり、objectは選択したアイテムを保持するためのプロパティですViewModelSelectedViewModelobject

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>
于 2012-06-08T16:21:24.080 に答える
1

のクラスに依存関係プロパティを追加し、それらをワールドに公開UserControlする内部のコントロールのプロパティにバインドします。UserControlこれによりUserControl、内部環境の安全性を確保しながら、必要なことをすべて実行しながら、適切なインターフェイスを外部に提示できます。

于 2012-06-08T16:02:39.070 に答える