手机
当前位置:查字典教程网 >编程开发 >C#教程 >在WPF中动态加载XAML中的控件实例代码
在WPF中动态加载XAML中的控件实例代码
摘要:本文实例讲述了在WPF中动态加载XAML中的控件的方法。分享给大家供大家参考,具体如下:usingSystem;usingSystem.Co...

本文实例讲述了在WPF中动态加载XAML中的控件的方法。分享给大家供大家参考,具体如下:

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.Xml; using System.Windows.Markup; /* * 功能:测试WPF中动态加载XAML中的控件 * 并加到指定的子节点中。 * 作者:Kagula * 时间:2012-09-20 * 环境:VS2008 .NET FRAMEWORK 3.5 * 参考资料:[1]《Application=Code+Markup 读书笔记 19》 * http://space.itpub.net/15123181/viewspace-423015 * [2]《Pack URIs in Windows Presentation Foundation》 * http://technet.microsoft.com/en-US/library/aa970069(v=vs.90) */ namespace testXAMLLoad { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); //LoadEmbeddedXaml(); //LoadEmbeddedXaml2(); LoadEmbeddedXaml3(); } //从字符串中加载 public void LoadEmbeddedXaml() { Title = "Load Embedded Xaml"; string strXaml = "<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'" + " Foreground='LightSeaGreen' FontSize='16pt' Width='128' Height='32'>" + " From String Object!</Button>"; StringReader strreader = new StringReader(strXaml); XmlTextReader xmlreader = new XmlTextReader(strreader); object obj = XamlReader.Load(xmlreader); grid1.Children.Add((UIElement)obj); } //从外部文件中加载 Button控件 public void LoadEmbeddedXaml2() { XmlTextReader xmlreader = new XmlTextReader("d:a.xaml"); UIElement obj = XamlReader.Load(xmlreader) as UIElement; grid1.Children.Add((UIElement)obj); } //从资源文件中加载 public void LoadEmbeddedXaml3() { //Build Action = Resource,Do not Copy,无相应cs文件 Uri uri = new Uri("/LoadXamlResource.xaml",UriKind.Relative); Stream stream =Application.GetResourceStream(uri).Stream; //FrameworkElement继承自UIElement FrameworkElement obj =XamlReader.Load(stream) as FrameworkElement; grid1.Children.Add(obj); } } }

xaml文件中的清单

<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Foreground='LightSeaGreen' FontSize='16pt' Width='128' Height='32'> From File Object! </Button>

希望本文所述对大家C#程序设计有所帮助。

【在WPF中动态加载XAML中的控件实例代码】相关文章:

C#启动和停止windows服务的实例代码

C# 大小写转换(金额)实例代码

C#实现大数字运算的实例代码

C#基础 延迟加载介绍与实例

C#动态执行字符串(动态创建代码)的实例代码

C#中通过API实现的打印类 实例代码

Treeview动态添加用户控件传值和取值的实例代码

C#反射在实际应用中的实例代码

C#委托初级使用的实例代码

C# 手动/自动保存图片的实例代码

精品推荐
分类导航