我在ItemsSource綁定到一個ObservableCollection在datagrid中,如何在使用CompositeCollection時爲每行綁定不同的ItemsSource?
<DataGrid ItemsSource="{Binding Items}">
中的ObservableCollection每個項目也有一個字符串的ObservableCollection一個DataGrid。
其中一列是包含ComboBox的DataGridTemplateColumn。我希望每行的ComboBox包含該行ViewModel中字符串的ObservableCollection中的項目。如果我正常綁定它,這是有效的。但是,我似乎無法讓它工作,如果我使用CompositeCollection。
<DataGridTemplateColumn Header="Column Title">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox SelectedValue="{Binding Selected, UpdateSourceTrigger=PropertyChanged}">
<ComboBox.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding ???}" />
<ComboBoxItem>
<TextBlock>
<Hyperlink Command="{Binding DataContext.EditList, Source={x:Reference myGridName}}">Edit List</Hyperlink>
</TextBlock>
</ComboBoxItem>
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
我不確定綁定使用什麼來使其工作。如果沒有CompositeCollection,我可以簡單地做:
<ComboBox ItemsSource="{Binding SubItems}">
在尋找,我知道你需要設置一個信號源的CollectionContainer,但大多數的例子是爲它設置一個靜態列表的所有行相同。我需要每行綁定到該行的ViewModel中的ObservableCollection。
我已經試過:
<CollectionContainer Collection="{Binding DataContext.SubItems, RelativeSource={RelativeSource AncestorType=ComboBox}}" />
但導致的錯誤:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ComboBox', AncestorLevel='1'' ...
使用代理建議解決了問題 – drgnlrds