[英]WPF Binding Sibling Collection to a Child ListBox Control
這很難解釋,但我會盡力而為。 我有一個包含兩個集合的ViewModel對象。
public class ParentViewModel
{
public ObservableCollection<Child1> ChildCollection1 {get;set;}
public ObservableCollection<Child2> ChildCollection2 { get;set; }
}
在XAML視圖文件中,數據上下文的設置如下所示:
// populate the child1 and child 2 collections
this.DataContext = ParentViewModel;
在XAML代碼中,所有內容都在DataGrid控件內。 由於子對象具有一些需要在大多數datagrid列中顯示的字段,因此將DataGrid控件的ItemsSource設置為Child1Collection。 在一個DataGrid列之一是一個ListBox控件。 我希望該ListBox控件使用Child2Collection作為ItemsSource。
我怎樣才能做到這一點?
您可以使用ElementName
或RelativeResource
例
使用ElementName
<DataGrid x:Name="dGrid"
ItemsSource="{Binding ChildCollection1}">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding DataContext.ChildCollection2,ElementName=dGrid}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
使用RelativeSource
<DataGrid ItemsSource="{Binding ChildCollection1}">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding DataContext.ChildCollection2,RelativeSource={RelativeSource FindAncestor,AncestorType=DataGrid}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.