Changing DataTemplate TextBlock Property at Runtime

て烟熏妆下的殇ゞ 提交于 2019-12-04 06:01:57

问题


I have a DataTemplate defined as follows:

I am accessing it at runtime using the code below:

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

And now I want to change the textblock property to something how can I do that? It always appears to be blank.


回答1:


A DataTemplate is a template for creating the content. When calling LoadContent on the template, it creates the content defined by that template. Therefore, when you make changes to the TextBlock, it is only being applied to that one instance of the content, and not to the DataTemplate itself.

I'm assuming you need to do this to generate a binding based on a property passed in to the function. You can do this by generating the Template directly in code. It is a lot harder to understand than XAML, but this should do the trick:

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

        return new DataTemplate { VisualTree = factory };
    }


来源:https://stackoverflow.com/questions/2381740/changing-datatemplate-textblock-property-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!