Create Button from Xaml string : Xaml « Windows Presentation Foundation « C# / CSharp Tutorial






<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="DynamicXAML" Height="300" Width="300">
  <Grid Name="grid1" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Window>
//File:Window.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Markup;
using System.Xml;
using System.IO;

namespace WpfApplication1
{

  public partial class Window1 : System.Windows.Window
  {

    public Window1()
    {
      InitializeComponent();

      StringReader sr = new StringReader(@"<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 
        Foreground='BurlyWood' FontSize='20pt'>Click Me!</Button>");

      XmlReader reader = XmlReader.Create(sr);

      Button dynamicButton = (Button)XamlReader.Load(reader);

      this.grid1.Children.Add(dynamicButton);

      dynamicButton.Click += button1_Click;
   
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
      MessageBox.Show("Dynamic Button Loaded From XAML String");
    }

  }
}
WPF Create Button From Xaml String








24.154.Xaml
24.154.1.Property InheritanceProperty Inheritance
24.154.2.Attached PropertiesAttached Properties
24.154.3.Property Element SyntaxProperty Element Syntax
24.154.4.Embedded Code in Window.xamlEmbedded Code in Window.xaml
24.154.5.Xaml Button with namespaceXaml Button with namespace
24.154.6.Markup Extensions for ButtonMarkup Extensions for Button
24.154.7.Markup Extensions with Property Elements.xamlMarkup Extensions with Property Elements.xaml
24.154.8.Inner element with xml namespaceInner element with xml namespace
24.154.9.Embedded code for ApplicationEmbedded code for Application
24.154.10.Set button properties with Linq styleSet button properties with Linq style
24.154.11.Xaml and Code behindXaml and Code behind
24.154.12.Use Linq to get control from a containerUse Linq to get control from a container
24.154.13.My First WPF App with code behindMy First WPF App with code behind
24.154.14.Create Button from Xaml stringCreate Button from Xaml string
24.154.15.Reference name defined in Xaml in cs fileReference name defined in Xaml in cs file
24.154.16.Insert new line character to xaml attributeInsert new line character to xaml attribute