執行時載入XAML檔案
阿新 • • 發佈:2018-12-22
XAML解析器
在WPF執行時,XAML解析器公開為2個類,只要使用任何一種.NET語言寫的應用程式,都可以在執行時使用XAML。通過這2個類,可以對XAML進行相關操作。
System.Windows.Markup.XamlReader
System.Windows.Markup.XamlWriter
使用XAML解析器動態操作Xaml
使用XamlReader可以解析Xaml檔案中的元素,並進行相關操作:資料繫結、事件繫結等。
//後臺程式碼
Window myWindow = null;
//退出using語句塊時,FileStream將立即被關閉;
using (FileStream fs=new FileStream("G:\\NetCode\\MyWindow.xaml" , FileMode.Open,FileAccess.Read))
{
myWindow = (Window)XamlReader.Load(fs);
}
myWindow.Show();
Button bt_close = (Button)myWindow.FindName("button1");
(myWindow.FindName("text2") as TextBlock).Text= "Hello World";
bt_close.Click += bt_close_Click;
<!-- MyWindow.xaml -->
<Window 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"
mc:Ignorable="d"
Title="MyWindow"
Width ="640" Height="480" Background="{x:Null}" AllowsTransparency="True" WindowStyle="None" WindowStartupLocation="CenterScreen">
<Grid x:Name="LayoutRoot">
<Ellipse Margin="64,102,68,121" Stroke="Black">
<Ellipse.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<TextBlock x:Name="text1" Margin="165,166,154,217" TextWrapping="Wrap" Text="第一個WPF應用程式介面" FontSize="24" FontWeight="Bold" TextAlignment="Center" Foreground="#FFF6F7EF"/>
<TextBlock x:Name="text2" Margin="205,206,154,217" />
<Button x:Name="button1" Content="退出" Height="28" Margin="255,0,269,185" VerticalAlignment="Bottom" Cursor="Hand" />
</Grid>
</Window>