C#/WPF:将DataGrid中的ComboBox ItemSource绑定到DataContext之外的元素

13

我想要做以下事情:

public List<Users> PreLoadedUserList { get; set; }
public List<RowEntries> SomeDataRowList { get; set; }

public class Users
{
    public int Age { get; set; }
    public string Name { get; set; }
}
public class SomeDataRowList 
{
    public int UserAge { get; set;
}

现在我的(WPF工具包)DataGrid看起来像这样:

<my:DataGrid AutoGenerateColumns="False" MinHeight="200" 
             ItemsSource="{Binding Path=SomeDataRowList}">
    <my:DataGridComboBoxColumn Header="Age" 
                               ItemsSource="{Binding Path=PreLoadedUserList}" 
                               DisplayMemberPath="Name" 
                               SelectedValueBinding="{Binding Path=UserAge}"/>

</my:DataGrid>
现在我的问题是,PreLoadedUserList 在 ItemSource (SomeDataRowList) 外部,我不知道如何绑定到外部的内容。我实际想要的是: - 在 ComboBox 中显示 PreLoadedUserList - 将所选 ComboboxItem.Age 的值设置为 RowEntries 的 SelectedItem.UserAge 的值
如果我的解释太奇怪,请告诉我 :-) 谢谢, 干杯
2个回答

24

我们开始了 :-)

<my:DataGridTemplateColumn Header="SomeHeader">
    <my:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox SelectedValuePath="UserAge" 
                SelectedValue="{Binding Age}" 
                DisplayMemberPath="Name" 
                ItemsSource="{Binding Path=DataContext.PreLoadedUserList, 
                    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" 
                IsReadOnly="True" Background="White" />
        </DataTemplate>
    </my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>

希望这也能帮助到其他人。

谢谢!


哇,我一直在试着使用“DataGridComboBoxColumn”,但是什么也没发生……但是魔法出现了!你的漂亮示例(使用模板)起作用了。谢谢! - Philippe Lavoie
这个帮助了我解决我的问题,Joseph。处理这些标题组合框是我的下一个任务。你的解决方案帮了我很多,节省了我很多时间。非常感谢。 - Tvd

0
如果RowEntries是一个自定义类,只需给它一个对PreLoadedUserList的引用。然后,每个实例都有一个指向它的指针,您可以在绑定中使用它。
只是一个建议,类名像Users和RowEntries表明它们是集合,但您的用法看起来像是项而不是集合。我会使用单数名称来避免任何混淆。我会这样做:
public List<User> PreLoadedUserList { get; set; }
public List<RowEntry> SomeDataRowList { get; set; }

public class User
{
    public int Age { get; set; }
    public string Name { get; set; }
}
public class RowEntry 
{
    public int UserAge { get; set; }
    public List<User> PreLoadedUserList { get; set; }
}

// at the point where both PreLoadedUserList is instantiated
// and SomeDataRowList is populated
SomeDataRowList.ForEach(row => row.PreLoadedUserList = PreLoadedUserList);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接