DataGridComboBoxColumn.ItemsSource のバインドの問題
-
19-09-2019 - |
質問
テーブルが 3 つあります。項目 - これはdatacontext-ナビゲーション列グループグループを備えています - ナビゲーション列カテゴリがあります。
DataGrid に両方の列 (カテゴリとグループ) を含めたいのですが、カテゴリを選択すると、グループ列には Category.Groups のみが表示されます。
私が取り組んでいるコードは次のとおりです。
<tk:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}">
<tk:DataGrid.Columns>
<!--Works-->
<tk:DataGridComboBoxColumn
Header="Categroy"
DisplayMemberPath="Title"
SelectedValuePath="CategoryId"
SelectedValueBinding="{Binding Group.Category.CategoryId}"
ItemsSource="{Binding Context.Categories,
Source={x:Static Application.Current}}"
/>
<!--Look at these two things:-->
<!--This does work-->
<tk:DataGridTemplateColumn>
<tk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ItemsControl
ItemsSource="{Binding Group.Category.Groups}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type data:Group}">
<TextBlock Text="{Binding Title}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</tk:DataGridTemplateColumn.CellTemplate>
</tk:DataGridTemplateColumn>
<!--But this does NOT work, even it's the same source-->
<!--Notice I even tried a dummy converter and doesnt reach there-->
<tk:DataGridComboBoxColumn
Header="Group"
DisplayMemberPath="Title"
SelectedValuePath="GroupId"
ItemsSource="{Binding Group.Category.Groups,
Converter={StaticResource DummyConverter}}"
SelectedValueBinding="{Binding Group.GroupId}"
/>
</tk:DataGrid.Columns>
</tk:DataGrid>
アップデート
問題は、ItemsSource プロパティを非静的バインディングに設定できないことだと思いますか?ItemsSource を {Binding}
とともに DummyConverter
それはコンバータ内で止まりません。カテゴリコンボボックスでは正常に動作します。
解決
データグリッド内の列はビジュアル ツリーに追加されないため、データコンテキストがありません。少し奇妙に聞こえますが、見てください ビンスのブログ, 、視覚的なレイアウトの良い例です。グリッドが描画されると、セルにはデータ コンテキストが設定され、通常のバインディング (静的リソースではなく) を使用してセル内のコンボ ボックス項目ソースを設定できます。
次のようにコンボ ボックス項目のソースにアクセスできます。
<dg:DataGridComboBoxColumn>
<dg:DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=MyBindingPath}" />
</Style>
</dg:DataGridComboBoxColumn.EditingElementStyle>
</dg:DataGridComboBoxColumn>
見てください ここ そしてまた ここ いくつかのコード用。また、次のことも必要になります。 非編集要素の項目ソースを設定します このように 役職
他のヒント
MVVMを使用していて、 ItemSource
列をウィンドウ データ コンテキスト内のオブジェクトのコレクションに変換します。10種類の方法を試したはずですが、 何も機能しませんでした 見つけるまで この答え.
秘訣は、 CollectionViewSource
グリッドの外側でそれをグリッド内で参照します。 StaticResource
. 。例えば、
<Window.Resources>
<CollectionViewSource x:Key="ItemsCVS" Source="{Binding MyItems}" />
</Window.Resources>
<!-- ... -->
<DataGrid ItemsSource="{Binding MyRecords}">
<DataGridComboBoxColumn Header="Column With Predefined Values"
ItemsSource="{Binding Source={StaticResource ItemsCVS}}"
SelectedValueBinding="{Binding MyItemId}"
SelectedValuePath="Id"
DisplayMemberPath="StatusCode" />
</DataGrid>