绑定到数据网格的 ItemsSource 集合属性,而不是单个项

本文关键字:属性 单个项 集合 ItemsSource 数据 数据网 网格 绑定 | 更新日期: 2023-09-27 18:31:43

我在尝试绑定集合中的某些属性而不是元素的属性时感到困惑。我什至不知道如何正确表达它...代码可能会更好地解释:以下是类型(不是实际代码,我已将其缩短为基础知识):

public class myType
{
    public int P {get;set;}
}
public class myTypeCollection : ObservableCollection<myType>
{
    public int Ptotal {get { return this.Items.Select(i=>i.P).Aggregate((c,t)=>t = t + c); }}
    public int Pmin { get { this.Items.Min(i => i.P); } } //concept
    public int Pmax { get { this.Items.Max(i => i.P); } } //concept
}

它们用于模板化控件,其 XAML 如下所示:(添加注释以使其尽可能清晰)

<!-- myGridObject = new myTemplatedControl(); -->
<!-- myGridObject.DataContext = new myTypeCollection(); -->
<!-- NOTE: collection obviously is NOT empty in the real code -->
<sdk:DataGrid ItemsSource={Binding DataContext}> 
    <sdk:DataGridTemplateColumn Width="Auto">
        <sdk:DataGridTemplateColumn.HeaderStyle>
            <Style TargetType="sdk:DataGridColumnHeader">
                <Setter Property="ContentTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <!-- ?????? write out Ptotal in the header of the column ??????? -->
                            <!-- This throws a binding-related ArgumentException -->
                            <TextBlock Text="{Binding ???? Ptotal ?????}" />
    <!-- closing tags cut off -->
    <sdk:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding P}" />
    <!-- closing tags cut off once more-->

{Binding P}按预期工作,因为P是项的属性,但是如何访问集合的属性,如PtotalPmin等?

感谢您抽出宝贵时间阅读本文。如果缺少任何信息,请指出来,我会发布它。

绑定到数据网格的 ItemsSource 集合属性,而不是单个项

我认为问题是 DataGrid 绑定到集合,并且每一行都绑定到单个项目,而不是集合。 您需要获得链上一层的访问权限(回到集合本身)。

如果您运行的是 Silverlight 4+,则可以使用相对源代码。 例如:

<TextBlock Text="{Binding Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType=sdk:DataGrid, AncestorLevel=1}, Path=DataContext.Count}"

否则,可以创建对上下文的静态访问,以通过绑定Source访问它

因此,您需要集合对象作为绑定源。

您需要这些:

相对源标记扩展

Binding.RelativeSource Property

像这样的东西(未经测试):

    <TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type myTemplatedControl}}, Path=DataContext.Ptotal}" />

如果数据网格位于自定义myTemplatedControl 中。我并不完全清楚什么是myGridObject。主要思想是:

正如 MSDN 文档所说:Binding.RelativeSource Gets or sets the binding source by specifying its location relative to the position of the binding target.

如果您坚持使用 x:Type 扩展,下面是一个关于它的链接,因此您可以将其与自定义控件一起使用:

X:类型

另一种方法是,如果命名容器元素(其中集合是数据上下文),则可以将该元素设置为绑定源:

<TextBlock Text="{Binding ElementName=yourElementName, Path=DataContext.Ptotal}" />

事实证明,客户改变了对网格标题的想法,他不希望在标题中显示总计。

顺便说一句,我必须尝试了 20 种不同的方法,包括在各种类型的转换器中进行修补,但我无法完成这个看起来并不那么简单的任务。

再次感谢您的有趣建议。