WPF XamlReader 和 XamlWriter

<window x:class="WpfApplication2.XamlReaderWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="XamlReaderWindow" height="300" width="300"><grid><grid.rowdefinitions><rowdefinition></rowdefinition><rowdefinition></rowdefinition></grid.rowdefinitions><stackpanel><button content="XAML Reader" x:name="btnReader" click="btnReader_Click"></button><button content="XAML Reader" x:name="btnReadFromStream" click="btnReadFromStream_Click"></button></stackpanel><stackpanel grid.row="1"><button content="BAML to XAML" x:name="btnWriter" click="btnWriter_Click"></button></stackpanel></grid></window>

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.Shapes;
using System.IO;
namespace WpfApplication2
{
    #region 说明
    //XamlReader 载入的 XAML 代码不能包含任何类型(x:Class)以及事件代码(x:Code),也就是说要XAML自身的代码才受支持
    //XAML 动态载入在使用动态换肤以及运行时加载等场景颇为有用
    //XamlReader 和 XamlWriter 有很多限制,比如我想把一批 Baml 转化为 Xaml,再比如我想指定 Baml 的理解,然后通过 Load 的方式载入,那么这些场景就无法通过 XamlReader 和 XamlWriter 完成 了。
    #endregion
    /// <summary>/// XamlReaderWindow.xaml 的交互逻辑    /// </summary>public partial class XamlReaderWindow : Window
    {
        public XamlReaderWindow()
        {
            InitializeComponent();
        }
        private void btnReader_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder("<window xmlns="\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" xmlns:x="\"http://schemas.microsoft.com/winfx/2006/xaml\"" title="\"Window" height="\"600\"" width="\"600\"">");            sb.Append("</window>");
            var window = (Window)System.Windows.Markup.XamlReader.Parse(sb.ToString());
            window.ShowDialog();
        }
        private void btnReadFromStream_Click(object sender, RoutedEventArgs e)
        {
            using (var stream=new FileStream(@"MainWindow.xaml", FileMode.Open))
            {
                var window = (Window)System.Windows.Markup.XamlReader.Load(stream);
                window.ShowDialog();
            }
        }
        private void btnWriter_Click(object sender, RoutedEventArgs e)
        {
            var xaml = System.Windows.Markup.XamlWriter.Save(new MainWindow());
            MessageBox.Show(xaml);
        }
    }
}

知识共享许可协议
《WPF XamlReader 和 XamlWriter》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

0 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     161.88ms