How to define a DataTemplate in code?

后端 未结 3 1605
终归单人心
终归单人心 2021-02-19 10:14

How can I create a DataTemplate in code (using C#) and then add a control to that DataTemplate?



        
相关标签:
3条回答
  • 2021-02-19 10:29

    You can add a control like a TextBlock using a FrameworkElementFactory. Then you can add the TextBlockto the VisualTree of the DataTemplate. Like so:

    //Create binding object and set as mode=oneway
    Binding binding = new Binding();
    binding.Path = new PropertyPath("SomePropertyPathName");
    binding.Mode = BindingMode.OneWay;
    
    //get textblock object from factory and set binding
    FrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock));
    textElement.SetBinding(TextBlock.TextProperty, binding);
    
    //apply textblock to datatemplate
    dataTemplate.VisualTree = textElement;
    
    0 讨论(0)
  • 2021-02-19 10:36

    As far as I know, the only way to create a DataTemplate in Silverlight is to use XamlReader. Basically you would just pass it the XAML as a string and it will give you back a DataTemplate. Byron's solution would apply to WPF but Silverlight (to the best of my knowledge) does not support FrameworkElementFactory.

    Scott Morrison: Defining Silverlight DataGrid Columns at Runtime

    Take note of option #2 for DataGridTemplateColumn.

    0 讨论(0)
  • 2021-02-19 10:54

    Microsoft has a good article over at MSDN: "Data Templating Overview." I would start there.

    Update: Eh, scratch that. I read over your requirement for "in code." I'll just leave the link here for whoever might stumble upon this post.

    0 讨论(0)
提交回复
热议问题