有人可以告诉我这是否可能吗?我有一个 WPF 数据网格,我想将数据网格的列标题绑定(bind)到后面代码中的属性/字段。
这就是我尝试过的。这是我的专栏代码。
<DataGridTextColumn Header="{Binding ElementName=frmAssetPPM, Path=HeaderProperty}"
这就是我添加到窗口 xaml 中的内容。
<Window .... Name="frmAssetPPM">
这是我在后面的代码中的属性定义:
private const string HeaderPropertyConstant = "Property";
private string _headerProperty = HeaderPropertyConstant;
public string HeaderProperty
{
get { return _headerProperty; }
set { _headerProperty = value; }
}
但是,当我运行该应用程序时,我在 VS 的输出窗口中显示此错误消息。
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')
有人可以告诉我我做错了什么吗?或者如果我能做到这一点?我在某处读到,列是一个单独的对象,这有时会导致复杂化。
最佳答案
有些东西很难绑定(bind),因为它们不是可视化树的一部分,例如弹出窗口或您的情况 - 数据网格标题。一个众所周知的解决方法是使用 Josh Smith 的 DataContextSpy。基本上,您将其实例化为资源并为其提供绑定(bind)。然后在其他地方使用该实例,您可以在其中利用它的数据上下文。网络上有很多示例,但是为了让您入门,类似这样的东西应该可以工作..
<DataGrid.Resources>
<DataContextSpy x:Key="dcSpy"
DataContext="{Binding ElementName=frmAssetPPM, Path=HeaderProperty}"/>
....
然后你的绑定(bind)就会起作用:
<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 ();
}
}
关于c# - 将 WPF 数据网格列标题绑定(bind)到代码后面的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30327254/