在WPF中靜態加載XAML中的控件實例代碼。本站提示廣大學習愛好者:(在WPF中靜態加載XAML中的控件實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是在WPF中靜態加載XAML中的控件實例代碼正文
本文實例講述了在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#法式設計有所贊助。