How to define a DataTemplate in code?

后端 未结 3 1603
终归单人心
终归单人心 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;
    

提交回复
热议问题