【问题标题】:Changing DataTemplate TextBlock Property at Runtime在运行时更改 DataTemplate TextBlock 属性
【发布时间】:2010-03-04 18:31:53
【问题描述】:

我有一个 DataTemplate 定义如下:

我在运行时使用下面的代码访问它:

  else
                {
                    template = (DataTemplate)FindResource("GridViewTextBlockDataTemplate");

                    var textblock = (TextBlock) template.LoadContent();
                    textblock.Text = "bye";

                    //textblock.SetBinding(TextBlock.TextProperty, new Binding("[" + current.Key + "]"));
                }

                var column = new GridViewColumn
                                 {
                                     Header = current.Key,
                                     CellTemplate = template  
                                 };

                                gridView.Columns.Add(column);
            }

现在我想将 textblock 属性更改为我该怎么做?它总是显示为空白。

【问题讨论】:

    标签: wpf datatemplate


    【解决方案1】:

    DataTemplate 是用于创建内容的模板。在模板上调用 LoadContent 时,它会创建该模板定义的内容。因此,当您对 TextBlock 进行更改时,它只会应用于该内容的一个实例,而不是应用于 DataTemplate 本身。

    我假设您需要这样做以根据传入函数的属性生成绑定。您可以通过直接在代码中生成模板来做到这一点。它比 XAML 更难理解,但这应该可以解决问题:

        private DataTemplate GenerateTextBlockTemplate(string property)
        {
            FrameworkElementFactory factory = new FrameworkElementFactory(typeof(TextBlock));
            factory.SetBinding(TextBlock.TextProperty, new Binding(property));
    
            return new DataTemplate { VisualTree = factory };
        }
    

    【讨论】:

    • 谢谢!我使用的是 FrameworkElementFactory,但后来我需要访问 TreeView.Items 属性等属性,该属性不能作为依赖属性使用。
    • 嗯,FrameworkElementFactory 是 XAML 解析器创建 DataTemplates 的方式...因此,如果您可以在 XAML 中执行此操作,则可以在代码中执行此操作。你到底需要做什么,这对你不起作用?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多