0
WPFでは、要素のグリッドを定義しました。それらは、ViewModel
の配列内のオブジェクトのプロパティに応じて表示または折りたたまれます。 XAMLファイルで わずかに異なるDataTemplate要素を再利用するには?
DataTemplate
は次のようになります。
<DataTemplate DataType="{x:Type implementationInputDevices:InputDevicesViewModel}">
<Grid Grid.Row="1" Grid.Column="0">
...
<TextBlock Grid.Row="1"
Grid.Column="0"
Text="{Binding MyArray[0].Name}"
Visibility="{Binding MyArray[0].Visible}"/>
<ComboBox Grid.Row="1"
Grid.Column="1"
Visibility="{Binding MyArray[0].Visible}"
SelectedItem="{Binding MyArray[0].Foo}"
ItemsSource="{Binding Bar}"/>
<TextBlock Grid.Row="2"
Grid.Column="0"
Text="{Binding MyArray[1].Name}"
Visibility="{Binding MyArray[1].Visible}"/>
<ComboBox Grid.Row="2"
Grid.Column="1"
Visibility="{Binding MyArray[1].Visible}"
SelectedItem="{Binding MyArray[1].Foo}"
ItemsSource="{Binding Bar}"/>
...
<TextBlock Grid.Row="n"
Grid.Column="0"
Text="{Binding MyArray[n-1].Name}"
Visibility="{Binding MyArray[n-1].Visible}"/>
<ComboBox Grid.Row="n"
Grid.Column="1"
Visibility="{Binding MyArray[n-1].Visible}"
SelectedItem="{Binding MyArray[n-1].Foo}"
ItemsSource="{Binding Bar}"/>
</Grid>
</DataTemplate>
あなたが見ることができるように、私はすべての行のための要素の同じブロックを使用しますが、わずかに異なる値を使用しています。 これは非常に不便です。新しい行を追加するには手動で調整する必要があり、(このグリッド内の)上の行を追加する必要がさらに増えます。
要素のセットを一度定義し、単純なコマンドで再利用することはできますか?このような何か:
<MyRowElement n="1" />
<MyRowElement n="2" />
...
<MyRowElement n="k" />
にネスト同じユーザーコントロール、です。この例を見て観察可能なコレクション? MyArray [index] .propertyにバインドする代わりに、各アイテムがテキストブロックとコンボボックスで構成されるように指定するリストボックスのようなコントロールにバインドされるオブジェクトの観察可能なコレクションを作成します。あなたはデータテンプレートセレクタであなたが望むものを達成することができますが、正直なところこのアプローチは私にとってはとても醜いものです –
質問のタイトルから強制タグを削除しました。なぜ[ここ](https://stackoverflow.com/help/tagging)を読んでください。 – dymanoid
ハードコードされたグリッドの代わりに、 'ItemsControl'を使うべきです。 'ItemsPanel'として' Grid'を使うことができます。 [この質問](https://stackoverflow.com/questions/16559186/wpf-sharedgridsize-group-with-itemscontrol-embedded-grids)から始めてください。 – dymanoid