There is a link to the var button

 var button = new Button(); button.ContentTemplate... 

How to implement XAML code programmatically?

XAML:

 <Button > <Button.ContentTemplate> <DataTemplate> <WrapPanel > <TextBlock /> </WrapPanel> </DataTemplate> </Button.ContentTemplate> </Button> 
  • one
    Eh, MVVM you do not have enough ... - MihailPw
  • Why manually create a contact? - Alex78191

1 answer 1

 DataTemplate template = new DataTemplate(); FrameworkElementFactory wrapPanel = new FrameworkElementFactory(typeof(WrapPanel)); FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock)); textBlock.SetValue(TextBlock.TextProperty, "some text");//добавим текст wrapPanel.AppendChild(textBlock); template.VisualTree = wrapPanel; button.ContentTemplate = template; 

The second option using XamlRedaer :

 string temp = @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> <WrapPanel> <TextBlock/> </WrapPanel> </DataTemplate>"; StringReader stringReader = new StringReader(temp); XmlReader xmlReader = XmlReader.Create(stringReader) DataTemplate template = XamlReader.Load(xmlReader) as DataTemplate; button.ContentTemplate = template; 
  • why in the first variant the error is with textBlock.Text = "1"; &? System.ArgumentException: "Не удается добавить текст "1", так как текст не является допустимым в данном элементе." `$ exception Unable to evaluate expression. ` - codename0082016
  • @ codename0082016, because textBlock in this case is not really a TextBlock instance. Updated the answer, see. - Gardes
  • On cool! I did not know how to create templates in code. - VladD
  • one
    @VladD, me too, until today) - Gardes