Launch a window with defined XAML

image_pdfimage_print


   
  

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     Title="Simple XAMl Viewer" Height="338" Width="1041" 
    Loaded="Window_Loaded" Closed="Window_Closed" WindowStartupLocation="CenterScreen" >
  <DockPanel  LastChildFill="True" >
    <Button DockPanel.Dock="Top"  Name = "btnViewXaml" Width="100" Height="40"
              Content ="View Xaml" Click="btnViewXaml_Click" />
    <TextBox AcceptsReturn ="True" Name ="txtXamlData"
       BorderBrush ="Blue" VerticalScrollBarVisibility="Auto" AcceptsTab="True" TextDecorations="None">
    </TextBox>
  </DockPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using System.Windows.Markup;

namespace WpfApplication1
{
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();
    }

    private void btnViewXaml_Click(object sender, RoutedEventArgs e)
    {
      File.WriteAllText("YourXaml.xaml", txtXamlData.Text);
      Window myWindow = null;
      try
      {
        using (Stream sr = File.Open("YourXaml.xaml", FileMode.Open))
        {
          myWindow = (Window)XamlReader.Load(sr);
          myWindow.ShowDialog();
        }
      }
      catch (Exception ex)
      { MessageBox.Show(ex.Message); }
    }
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        txtXamlData.Text =
        "<Window xmlns="http://schemas.microsoft.com"
        + "/winfx/2006/xaml/presentation"
"
        + "xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml""
        + " Height ="400" Width ="500" WindowStartupLocation="CenterScreen">
"
        + "<StackPanel>
"
        + "</StackPanel>
"
        + "</Window>";
    }
    private void Window_Closed(object sender, EventArgs e)
    {
      File.WriteAllText("YourXaml.xaml", txtXamlData.Text);
    }
  }
}