【问题标题】:WPF decomposition - DataGridTemplateColumnWPF 分解 - DataGridTemplateColumn
【发布时间】:2010-10-16 20:13:50
【问题描述】:

我正在尝试将自定义 DataGrid 列定义移动到用户控件中。

MyComboBoxColumn.xaml

<dg:DataGridTemplateColumn 
    x:Class="WpfDecomposition.MyComboBoxColumn"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WpfToolkit"
    x:Name="_this"
    >

    <dg:DataGridTemplateColumn.Header>
        <Button Content="{Binding MyHeader, ElementName=_this}" ></Button>
    </dg:DataGridTemplateColumn.Header>

</dg:DataGridTemplateColumn>

MyComboBoxColumn.cs

public partial class MyComboBoxColumn : DataGridTemplateColumn
{
    public MyComboBoxColumn()
    {
        InitializeComponent();
    }

    public static DependencyProperty MyHeaderProperty = 
        DependencyProperty.Register("MyHeader", typeof(string), typeof(MyComboBoxColumn), new PropertyMetadata("TEST"));
}

主窗口 XAML:

<dg:DataGrid CanUserAddRows="True" AutoGenerateColumns="False">
    <dg:DataGrid.Columns>
        <my:MyComboBoxColumn />
    </dg:DataGrid.Columns>
</dg:DataGrid>

我希望在列标题中看到一个“TEST”按钮,但我看到的是空按钮。看来绑定坏了。怎么了?

【问题讨论】:

    标签: wpf wpftoolkit datagridtemplatecolumn


    【解决方案1】:

    它不起作用,因为它找不到名称为 _this 的元素。当我在 Visual Studio 中调试您的代码时,在“输出”窗口中出现以下错误:

    System.Windows.Data 错误:4:不能 通过参考查找绑定源 '元素名称=_this'。 绑定表达式:路径=我的标题; 数据项=空;目标元素是 '按钮'(名称='TestButton');目标 属性是“内容”(类型“对象”)

    至于为什么找不到它-我认为这是因为 WPF 绑定使用可视化树来查找绑定的源。在这种情况下,MyComboBoxColumn 不在可视化树中,因此它找不到具有该名称的元素。

    我也尝试使用 RelativeSource 来查找元素,但这也不起作用 - 可能出于相同的原因。

    我唯一能做的就是在构造函数中将按钮的DataContext 设置为列本身:

    public MyComboBoxColumn()
    {
        InitializeComponent();
    
        this.TestButton.DataContext = this;
    }
    

    然后在 XAML 中更改绑定:

    <tk:DataGridTemplateColumn.Header>
        <Button Content="{Binding Path=MyHeader}" x:Name="TestButton" />
    </tk:DataGridTemplateColumn.Header>
    

    这似乎不是最好的方法,但至少它有效。

    【讨论】:

      【解决方案2】:

      如果您不想或不能在构造函数中设置DataContext(例如在代码中动态创建列时),请将列的Header 属性设置为您要绑定到的对象(数据上下文),然后您可以在HeaderStyle 数据模板中绑定到该对象。

      详情请见this question

      【讨论】:

        猜你喜欢
        • 2014-06-12
        • 2013-06-30
        • 2012-10-13
        • 2011-03-03
        • 2011-02-06
        • 2019-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多