简体   繁体   English

在运行时加载XAML

[英]Loading XAML in run time

I want to load a particular piece of XAML code in runtime. 我想在运行时加载特定的XAML代码。 Using the below code, I can load the xaml present in a txt file. 使用以下代码,我可以加载存在于txt文件中的xaml。

private void btnLoadXAML_Click(object sender, RoutedEventArgs e)
{
  try
  {

    string LoadedFileName = @"C:\test\sample.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);
}
}

The above code will actually create a new Grid control and load the XAML present in the text file and create the controls as per the code. 上面的代码实际上将创建一个新的Grid控件,并加载文本文件中存在的XAML,然后根据代码创建控件。 Consider the below code... 考虑下面的代码...

<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">

The above is the "Window" tag. 上面是“窗口”标签。 I just need a couple of properties of it in run time. 在运行时,我只需要几个属性。 For eg: the below code 例如:下面的代码

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"

I don't want the above to hard code in the xaml but to insert it in run time, how can I do that? 我不希望以上内容在xaml中进行硬编码,而是在运行时插入它,我该怎么做? I tried the method I mentioned initially but I get run time error. 我尝试了最初提到的方法,但出现运行时错误。

XAML loaded through XamlReader has some restrictions compared to normal compiled XAML files, including not depending on code-behind, since it is just parsing rather than compiling. 与普通的已编译XAML文件相比,通过XamlReader加载的XAML具有一些限制,包括不依赖于背后的代码,因为它只是解析而不是编译。 In your case the Window you're trying to use has the usual x:Class attribute which specifies its code-behind component. 在您的情况下,您尝试使用的Window具有通常的x:Class属性,该属性指定其代码隐藏组件。 If you're just using it to load some properties you should be able to strip that attribute out, either from the saved file or by using File.ReadAllText and XamlReader.Parse to modify at runtime. 如果仅使用它来加载某些属性,则应该能够从保存的文件中删除该属性,也可以使用File.ReadAllTextXamlReader.Parse在运行时进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM