WPF - 运行时加载XAML文件

    xiaoxiao2021-04-14  83

    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>
    转载请注明原文地址: https://ju.6miu.com/read-670725.html

    最新回复(0)