Changing DataTemplate TextBlock Property at Runtime

后端 未结 1 1783
耶瑟儿~
耶瑟儿~ 2021-01-28 09:07

I have a DataTemplate defined as follows:

I am accessing it at runtime using the code below:

  else
                {
                   


        
相关标签:
1条回答
  • 2021-01-28 09:21

    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 };
        }
    
    0 讨论(0)
提交回复
热议问题