【问题标题】:WPF Binding Sibling Collection to a Child ListBox ControlWPF 将同级集合绑定到子 ListBox 控件
【发布时间】:2014-07-18 16:38:14
【问题描述】:

这有点难以解释,但我会尽力而为。我有一个包含两个集合的 ViewModel 对象。

public class ParentViewModel
{
    public ObservableCollection<Child1> ChildCollection1 {get;set;} 
    public ObservableCollection<Child2> ChildCollection2 { get;set; }
}

在 XAML 视图文件中,datacontext 设置如下:

// populate the child1 and child 2 collections
this.DataContext = ParentViewModel;

在 XAML 代码中,一切都在 DataGrid 控件中。 DataGrid 控件的 ItemsSource 设置为 Child1Collection,因为子对象具有一些需要在大多数数据网格列中显示的字段。在 DataGrid 的其中一列中是一个 ListBox 控件。我希望 ListBox 控件使用 Child2Collection 作为 ItemsSource。

我该怎么做?

【问题讨论】:

  • 看起来您的视图模型有误。从技术上讲,DataGrid 只需要 1 个集合,但是每个项目(在集合中)可能有另一个集合,...这意味着它取决于您希望如何为 @987654326 中的每个项目用 ChildCollection2 填充 ListBox @.
  • 我期待这个答案! :) 我想我收藏的每件商品都会有另一个收藏,正如您所建议的那样。谢谢!
  • ChildCollection2 是否会为 ChildCollection1 的每个元素保存相同的值?发布要放入此 ListBox 的 DataGridTemplateColumn 的 xaml。您可以做您想做的事情,但我想看看您采取的方法来帮助您迈出最后一步。

标签: c# wpf xaml


【解决方案1】:

您可以使用ElementNameRelativeResource

例子

使用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    相关资源
    最近更新 更多