【问题标题】:WPF DataGridTextColumn header bindingWPF DataGridTextColumn 标题绑定
【发布时间】:2012-04-19 21:26:27
【问题描述】:

我有一个绑定不起作用的代码

<DataGridTextColumn Header="{Binding LocalizedText.Task_Toolbar_AddButton}" />

对于按钮:

<Button x:Name="addTaskButton" Click="addTaskButton_Click">
<TextBlock Text="{Binding LocalizedText.Task_Toolbar_AddButton, Mode=OneWay}" />
</Button>

它工作正常,但对于 datagrid 标题根本不起作用。

【问题讨论】:

  • 标题不在逻辑树中...

标签: wpf binding datagrid header


【解决方案1】:

查看 Josh Smith 关于 DataContext Spy 的博客,其中 DataContextSpy 类使用 Hillberg 的 Freezable 技巧从不在逻辑树中的对象获取继承上下文的访问权限。 DataContextSpy 很简单,应该可以在很多场景下复用。

以下是在标题上使用它的方法(我一直都在使用它,不仅在 DataGrid.Headers 上):

    <DataGrid...
    <DataGrid.Resources>
        <myNamespaces:DataContextSpy x:Key="dcSpy" DataContext="{LocalizedText}"/>
         .......

    <DataGridTemplateColumn Header="{Binding Source={StaticResource dcSpy}, Path=DataContext.Task_Toolbar_AddButton}">

编辑: 我在他的博客上好像找不到,可能是他存档了,所以在这里,我只是为你添加它。粘贴它,如上所示在 XAML 中引用它,然后使用它的 DataContext 提取您要绑定的数据:

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 ();
    }
}

【讨论】:

  • 嗨,丹尼斯,非常感谢您的回答。我的 xaml &lt;UserControl.DataContext&gt; &lt;locale:SelectCultureViewModel SelectedCulture="hy-AM" /&gt; &lt;/UserControl.DataContext&gt; 中有一个代码,在输入您发送给我的代码后,我收到一个错误 Error 1 '{LocalizedText}' value is not a valid MarkupExtension expression。无法解析命名空间“schemas.microsoft.com/winfx/2006/xaml/presentation”中的“LocalizedText”。 'LocalizedText' 必须是 MarkupExtension 的子类...
  • 哦,天哪,我忘了把绑定放在那里,哈哈,对不起:),所以放:DataContext="{Binding LocalizedText}"
猜你喜欢
  • 2013-12-10
  • 2013-06-22
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多