Create DataTemplate in code behind

前端 未结 3 773
野的像风
野的像风 2020-11-27 05:12

How do i add controls to datatemplates programmatically?

For Example. Below I\'ve created TextBlock and DataTemplate.

TextBlock text = new TextBlock(         


        
3条回答
  •  忘掉有多难
    2020-11-27 05:40

    Although Archedius's method works, officially it is deprecated and instead recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class like this...

    public DataTemplate Create(Type type)
    {
        StringReader stringReader = new StringReader(
        @" 
                <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/> 
            ");
        XmlReader xmlReader = XmlReader.Create(stringReader);
        return XamlReader.Load(xmlReader) as DataTemplate;
    }
    

    Official line taken from msdn: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx

    Code example from Fredrik Hedblad's post here: Problems with XamlReader generating DataTemplate

提交回复
热议问题