XAML(extensible application markup language)發音爲「zammel」,是用於實例化.net對象的標記語言。html
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfXaml { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); LoadXaml(); } private void LoadXaml() { using var fileReader = new FileStream("../../../Test.xaml", FileMode.Open); DependencyObject rootElement = (DependencyObject)XamlReader.Load(fileReader); this.Content = rootElement; var btn = (Button)LogicalTreeHelper.FindLogicalNode(rootElement, "A"); if (btn != null) btn.Click += Btn_Click; } private void Btn_Click(object sender, RoutedEventArgs e) { MessageBox.Show("showMe"); } } }
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfXaml"> <Button Content="123" Width="100" Height="30" Name="A"></Button> <Button Content="456" Width="100" Height="30" Name="B"></Button> </StackPanel>
注意:這種直接加載xaml的方式並無使用打包成資源的baml速度快express
<Window x:Class="WpfXaml.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfXaml" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> </Grid> </Window>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"是WPF核心名稱空間,包含WPF因此類,包括構建用戶界面的控件
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"是XAML名稱空間,包含XAML的實用特效
x:Class="WpfXaml.MainWindow"
Class特性告訴XAML解釋器用指定名稱生成一個新類,該類是主窗口的部分類(partial,即MainWindow.g.i.cs)。該類包含了 InitializeComponent()方法。編程
<Grid x:Name="Grid"> </Grid>
Name特性告訴XAML解釋器爲部分類添加名稱爲Grid的字段後端
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid Grid;