正在运行时加载XAML



我想在运行时加载一段特定的XAML代码。使用下面的代码,我可以加载一个txt文件中的xaml。

private void btnLoadXAML_Click(object sender, RoutedEventArgs e)
{
  try
  {
    string LoadedFileName = @"C:testsample.txt";
    //Load the file
    FileStream Fs = new FileStream(@LoadedFileName, FileMode.Open);
    Grid grdToLoad = new Grid();
    grdToLoad.Height = 210;
    grdToLoad.Width = 400;
    grdToLoad = System.Windows.Markup.XamlReader.Load(Fs) as Grid;
    grdLoadXAML.Children.Add(grdToLoad);
    Fs.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
}

上面的代码实际上将创建一个新的Grid控件,并加载文本文件中的XAML,并根据代码创建控件。请考虑以下代码。。。

<Window x:Class="MyWPF.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title=" " 
    Height="270" 
    Width="420" 
    Background="{x:Null}" 
    Foreground="#FFFFFFFF" 
    ShowInTaskbar="False"
    WindowStartupLocation="CenterScreen" 
    ResizeMode="NoResize" 
    WindowStyle="None" 
    AllowsTransparency="True" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d">

上面是"Window"标签。我只需要它在运行时的几个属性。例如:以下代码

WindowStyle="None" AllowsTransparency="True" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"

我不想在xaml中硬编码上面的内容,而是在运行时插入它,我该怎么做?我尝试了我最初提到的方法,但我遇到了运行时错误。

与正常编译的XAML文件相比,通过XamlReader加载的XAML有一些限制,包括不依赖于代码隐藏,因为它只是解析而不是编译。在您的情况下,您尝试使用的Window具有通常的x:Class属性,该属性指定其代码隐藏组件。如果您只是使用它来加载一些属性,那么您应该能够从保存的文件中剥离该属性,或者在运行时使用File.ReadAllTextXamlReader.Parse进行修改。

最新更新