在WPF中动态加载XAML中的控件实例代码
本文实例讲述了在WPF中动态加载XAML中的控件的方法。分享给大家供大家参考,具体如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Data;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Imaging;
usingSystem.Windows.Navigation;
usingSystem.Windows.Shapes;
usingSystem.IO;
usingSystem.Xml;
usingSystem.Windows.Markup;
/*
*功能:测试WPF中动态加载XAML中的控件
*并加到指定的子节点中。
*作者:Kagula
*时间:2012-09-20
*环境:VS2008.NETFRAMEWORK3.5
*参考资料:[1]《Application=Code+Markup读书笔记19》
*http://space.itpub.net/15123181/viewspace-423015
*[2]《PackURIsinWindowsPresentationFoundation》
*http://technet.microsoft.com/en-US/library/aa970069(v=vs.90)
*/
namespacetestXAMLLoad
{
///<summary>
///InteractionlogicforWindow1.xaml
///</summary>
publicpartialclassWindow1:Window
{
publicWindow1()
{
InitializeComponent();
//LoadEmbeddedXaml();
//LoadEmbeddedXaml2();
LoadEmbeddedXaml3();
}
//从字符串中加载
publicvoidLoadEmbeddedXaml()
{
Title="LoadEmbeddedXaml";
stringstrXaml="<Buttonxmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'"+
"Foreground='LightSeaGreen'FontSize='16pt'Width='128'Height='32'>"+
"FromStringObject!</Button>";
StringReaderstrreader=newStringReader(strXaml);
XmlTextReaderxmlreader=newXmlTextReader(strreader);
objectobj=XamlReader.Load(xmlreader);
grid1.Children.Add((UIElement)obj);
}
//从外部文件中加载Button控件
publicvoidLoadEmbeddedXaml2()
{
XmlTextReaderxmlreader=newXmlTextReader("d:\\a.xaml");
UIElementobj=XamlReader.Load(xmlreader)asUIElement;
grid1.Children.Add((UIElement)obj);
}
//从资源文件中加载
publicvoidLoadEmbeddedXaml3()
{
//BuildAction=Resource,DonotCopy,无相应cs文件
Uriuri=newUri("/LoadXamlResource.xaml",UriKind.Relative);
Streamstream=Application.GetResourceStream(uri).Stream;
//FrameworkElement继承自UIElement
FrameworkElementobj=XamlReader.Load(stream)asFrameworkElement;
grid1.Children.Add(obj);
}
}
}
xaml文件中的清单
<Buttonxmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Foreground='LightSeaGreen' FontSize='16pt' Width='128' Height='32'> FromFileObject! </Button>
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#程序设计之线程使用技巧总结》、《C#操作Excel技巧总结》、《C#中XML文件操作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#数组操作技巧总结》及《C#面向对象程序设计入门教程》
希望本文所述对大家C#程序设计有所帮助。