在代码隐藏中将 WPF 数据网格列 header 绑定到 属性

Bind a WPF datagrid column header to property in code behind

谁能告诉我这是否可行。我有一个 WPF 数据网格,我想将数据网格的列 headers 绑定到后面代码中的 properties/fields。

这就是我尝试过的方法。这是我的专栏代码。

<DataGridTextColumn  Header="{Binding ElementName=frmAssetPPM, Path=HeaderProperty}" 

这就是我添加到 window xaml 中的内容。

<Window .... Name="frmAssetPPM">

这是我在后面的代码中的 属性 定义:

private const string HeaderPropertyConstant = "Property";
private string _headerProperty = HeaderPropertyConstant;

public string HeaderProperty 
{
    get { return _headerProperty; }
    set { _headerProperty = value; }
}

但是,当我 运行 应用程序时,我在 VS 的输出 window 中收到此错误消息。

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=HeaderProperty; DataItem=null; target element is 'DataGridTextColumn' (HashCode=47624635); target property is 'Header' (type 'Object')

有人可以告诉我我做错了什么吗?或者如果我能做到这一点?我在某处读到,列是单独的 object,这有时会导致并发症。

有些东西很难绑定,因为它们不是可视化树的一部分,例如弹出窗口或您的情况 - 数据网格 headers。一个众所周知的解决方法是使用 Josh Smith 的 DataContextSpy。基本上,您将其实例化为资源并为其提供绑定。然后在其他地方使用该实例,在那里您可以利用它的数据上下文。网络上有很多示例,但为了让您入门,像这样的东西应该可行..

<DataGrid.Resources>
    <DataContextSpy x:Key="dcSpy" 
                    DataContext="{Binding  ElementName=frmAssetPPM, Path=HeaderProperty}"/>
 ....

那么您的绑定将起作用:

<DataGridTextColumn  Header="{Binding Source={StaticResource dcSpy}, Path=DataContext}" 

这是 Josh Smith 的代码,如果您在网上找不到的话:

public class DataContextSpy : Freezable
{
    public DataContextSpy ()
    {
        // This binding allows the spy to inherit a DataContext.
        BindingOperations.SetBinding (this, DataContextProperty, new Binding ());
    }

    public object DataContext
    {
        get { return GetValue (DataContextProperty); }
        set { SetValue (DataContextProperty, value); }
    }

    // Borrow the DataContext dependency property from FrameworkElement.
    public static readonly DependencyProperty DataContextProperty = FrameworkElement
        .DataContextProperty.AddOwner (typeof (DataContextSpy));

    protected override Freezable CreateInstanceCore ()
    {
        // We are required to override this abstract method.
        throw new NotImplementedException ();
    }
}