Create Button from Xaml string


   
  
<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=&#039;http://schemas.microsoft.com/winfx/2006/xaml/presentation&#039; 
        Foreground=&#039;BurlyWood&#039; FontSize=&#039;20pt&#039;>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");
    }

  }
}

   
    
     


Reference name defined in Xaml in cs file


   
  
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="WpfApplication1.IndexOfSample" 
  WindowTitle="UIElementCollection IndexOf Sample">
    <DockPanel Name="ParentElement">
        <TextBlock DockPanel.Dock="Top" Name="TxtDisplay"></TextBlock>

        <Button DockPanel.Dock="Top" Click="FindIndex">What is the Index Number
            of the Element Just Added?</Button>
        <DockPanel Name="MainDisplayPanel">
            <TextBlock DockPanel.Dock="Top">Text 1</TextBlock>
            <TextBlock DockPanel.Dock="Top">Text 2</TextBlock>
        </DockPanel>
    </DockPanel>
</Page>

//File:Window.xaml.cs

namespace WpfApplication1 {
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;

    public partial class IndexOfSample {

    
    void FindIndex(object sender, RoutedEventArgs e)
    {
      TextBlock newText = new TextBlock();
      MainDisplayPanel.Children.Add(newText);
      newText.Text = "New element #" ;
      DockPanel.SetDock(newText,Dock.Top);
      TxtDisplay.Text = MainDisplayPanel.Children.IndexOf(newText)+"";
    }
  }
}

   
    
     


Insert new line character to xaml attribute


   
  

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        xmlns:src="clr-namespace:MyNameSpace.EnvironmentInfo2" 
        Title="Environment Info">
    <Window.Resources>
        <src:FormattedMultiTextConverter x:Key="conv" />
    </Window.Resources>

    <TextBlock>
        <TextBlock.Text>
            <MultiBinding Converter="{StaticResource conv}"
                          ConverterParameter=
"Operating System Version: {0}
&amp;#x000A;.NET Version: {1}
&amp;#x000A;Machine Name: {2}
&amp;#x000A;User Name: {3}" >
                <Binding Source="{x:Static s:Environment.OSVersion}" />
                <Binding Source="{x:Static s:Environment.Version}" />
                <Binding Source="{x:Static s:Environment.MachineName}" />
                <Binding Source="{x:Static s:Environment.UserName}" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</Window>
//File:Window.xaml.cs
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace MyNameSpace.EnvironmentInfo2
{
    public class FormattedMultiTextConverter : IMultiValueConverter
    {
        public object Convert(object[] value, Type typeTarget, 
                              object param, CultureInfo culture)
        {
            return String.Format((string) param, value);
        }
        public object[] ConvertBack(object value, Type[] typeTarget, 
                                    object param, CultureInfo culture)
        {
            return null;
        }
    }
}

   
    
     


Use XamlReader to read Xaml xml file

   
  


<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="FlowDocReader Load/Save Sample" Width="640" Height="480">
  <StackPanel>
    <FlowDocumentReader Name="FlowDocRdr" Grid.Row="1"/>
  </StackPanel>
</Window>
//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.IO;
using System.Windows.Markup;

namespace WpfApplication1
{

    public partial class Window1 : Window
    {

        public Window1()
        {
            InitializeComponent();

            FlowDocument content = null;
            
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "FlowDocument Files (*.xaml)|*.xaml|All Files (*.*)|*.*";

            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                FileStream xamlFile = openFile.OpenFile() as FileStream;
                if (xamlFile == null) return;
                else
                {   
                    try 
                    { 
                        content = XamlReader.Load(xamlFile) as FlowDocument; 
                        if (content == null) 
                            throw(new XamlParseException("The specified file could not be loaded as a FlowDocument."));
                    }
                    catch (XamlParseException e)
                    {
                        String error = "There was a problem parsing the specified file:

";
                        error += openFile.FileName;
                        error += "

Exception details:

";
                        error += e.Message;
                        System.Windows.MessageBox.Show(error);
                        return;
                    }
                    catch (Exception e) 
                    {
                        String error = "There was a problem loading the specified file:

";
                        error += openFile.FileName;
                        error += "

Exception details:

";
                        error += e.Message;
                        System.Windows.MessageBox.Show(error);
                        return;
                    }

                    FlowDocRdr.Document = content;
                }
            }
        }
    }
}

   
    
     


Use XamlReader to read a Xaml string and convert to a Control


   
  

<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=&#039;http://schemas.microsoft.com/winfx/2006/xaml/presentation&#039; 
        Foreground=&#039;BurlyWood&#039; FontSize=&#039;20pt&#039;>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");
    }

  }
}

   
    
     


HierarchicalDataTemplate and XmlDataProvider


   
   

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TreeViewSelectedValue">
  <FrameworkElement.Resources>
    <XmlDataProvider x:Key="myCourseData" XPath="/CourseData">
      <x:XData>
        <CourseData xmlns="">
          <CourseInfo>
            <CourseName>A</CourseName>
            <CourseWorkDay>Monday</CourseWorkDay>
            <CourseWorkDay>Tuesday</CourseWorkDay>
            <CourseWorkDay>Wednesday</CourseWorkDay>
            <CourseWorkDay>Thrusday</CourseWorkDay>
            <CourseWorkDay>Friday</CourseWorkDay>
            <CourseStartTime>8:00am</CourseStartTime>
            <CourseNumber>12345</CourseNumber>
          </CourseInfo>
          <CourseInfo>
            <CourseName>B</CourseName>
            <CourseWorkDay>Monday</CourseWorkDay>
            <CourseWorkDay>Tuesday</CourseWorkDay>
            <CourseStartTime>6:30am</CourseStartTime>
            <CourseNumber>98765</CourseNumber>
          </CourseInfo>
        </CourseData>
      </x:XData>
    </XmlDataProvider>
    <HierarchicalDataTemplate DataType="CourseInfo" ItemsSource ="{Binding XPath=CourseWorkDay}">
      <TextBlock Text="{Binding XPath=CourseName}" />
    </HierarchicalDataTemplate>
  </FrameworkElement.Resources>
  <StackPanel>
    <TreeView ItemsSource="{Binding Source={StaticResource myCourseData}, XPath=CourseInfo}" 
        Name="myTreeView" SelectedValuePath="CourseNumber"/>

    <TextBlock Margin="10">SelectedValuePath: </TextBlock>
    <TextBlock Margin="10" Text="{Binding ElementName=myTreeView, Path=SelectedValuePath}"/>
    <TextBlock Margin="10">SelectedValue: </TextBlock>
    <TextBlock Margin="10" Text="{Binding ElementName=myTreeView, Path=SelectedValue}"/>

  </StackPanel>     

</Page>

   
    
    
     


Xmldata island.xaml


   
   

<Window x:Class="ControlDemos.xmldataisland"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ControlDemos" Height="300" Width="300">
  <Window.Resources>
    <XmlDataProvider x:Key="MyCompany" XPath="/Company/Country">
      <x:XData>
        <Company xmlns="">
          <Country Name="USA">
            <Employee>A</Employee>
          </Country>
          <Country Name="England">
            <Employee>B</Employee>
          </Country>
          <Country Name="Japan">
            <Employee>C</Employee>
          </Country>
        </Company>
      </x:XData>
    </XmlDataProvider>
  </Window.Resources>
  <Grid>
    <StackPanel>
      <ListBox>
        <ListBox.ItemsSource>
          <Binding Source="{StaticResource MyCompany}" XPath="/Company/Country"/>
        </ListBox.ItemsSource>
        <ListBox.ItemTemplate>
          <DataTemplate>
            <StackPanel>
              <TextBlock>
                <TextBlock.Text>
                  <Binding XPath="Employee"/>
                </TextBlock.Text>
              </TextBlock>
              <TextBlock>
                <TextBlock.Text>
                  <Binding XPath="@Name"/>
                </TextBlock.Text>
              </TextBlock>
            </StackPanel>
          </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>
    </StackPanel>
  </Grid>
</Window>