在WPF中获取XAML代码

本文关键字:XAML 代码 获取 WPF | 更新日期: 2023-09-27 18:23:40

如何将窗口的XAML代码作为字符串获取,更改此字符串,并将此字符串作为窗口的XAML代码上载?

例如,我有

<Window x:Class="WpfApplication1.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:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ComboBox Margin="0,0,9,38" Name="button1" Height="82" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="132"></ComboBox>
    </Grid>
</Window>

我想把这个xaml代码放在最后的中

<Window x:Class="WpfApplication1.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:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ComboBox Margin="0,0,9,38" Name="button1" Height="82" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="132">
        <ComboBox.ItemTemplate>
             <DataTemplate>
                <local:d_dddw_imp_insurance_list />
             </DataTemplate>
        </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</Window>

在WPF中获取XAML代码

如果您将wpf/xaml与c#一起使用,visualstudio通常会将xaml代码编译为c#,以尽可能提高性能。如果你想要一些动态XAML,你需要使用XamlReader来读取XAML并显示在"自己"。

看看:通过运行时加载XAML XML

然后您可以更改或操作xaml并非常容易地显示结果。