通过运行时加载XAML XML?

13
我们正在将解决方案从Winforms迁移到WPF。我们有定制的XML定义,用于在运行时构建窗体。

由于XAML是基于XML的,我们能否使用XAML定义一个HelloWorldWindow.xml文件,并且可以在WPF应用程序中加载它而不需要任何CSharp文件的代码后台?我们将在运行时附加代码后台钩子。

如何在运行时附加代码后台?


你所说的这个 XML 文件是否是一个有效的 XAML 文件? - Steve Danner
@Steve,是的,这是一个有效的XAML文件。但我们希望在运行时附加代码实现。 - user90150
有一个应用了大部分MVVM概念的工作解决方案:我的解决方案 - Adolfo Perez
3个回答

19

使用此XAML创建一个名为Tempwin.xml的XML文件:

<UserControl 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300" Background="Transparent" >
<Border Background="Black" CornerRadius="10" BorderThickness="4" BorderBrush="RoyalBlue">
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Text="Sample Text" Foreground="White" Margin="2"></TextBlock>
        <TextBox Grid.Row="1" Margin="5"> </TextBox>
        <TextBlock Text="Sample Text 1" Grid.Row="2" Foreground="White" Margin="2"></TextBlock>
        <TextBox Grid.Row="3" Margin="5"></TextBox>
        <Ellipse Fill="Red" Height="100" Width="100" Grid.Row="4" Margin="0,10,0,0"></Ellipse>
    </Grid>
    </Border>

使用下面的XAML创建一个WPF示例应用程序:

<Window x:Class="WpfApplication12.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="600" Width="600">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>

    </Grid.RowDefinitions>

    <Button Height="25" Width="100" Margin="2" Click="Button_Click"> Show Content</Button>
    <Grid x:Name="content" Grid.Row="1" Margin="2">

    </Grid>
</Grid>

将下面的 C# 代码粘贴到 Button_Click 的代码后台

  StreamReader mysr = new StreamReader(@"D:\Tempwin.xml");
        FrameworkElement  rootObject = XamlReader.Load(mysr.BaseStream) as FrameworkElement;
        content.Children.Add(rootObject);

如果您想在运行时加载XAML,则不能在XAML文件中添加任何代码。因此,在创建XML之前,我已经删除了x:Class属性。

事件挂钩....

<UserControl 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300" Background="Transparent" >
<Border Background="Black" CornerRadius="10" BorderThickness="4" BorderBrush="RoyalBlue">
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Text="Sample Text" Foreground="White" Margin="2"></TextBlock>
        <TextBox Grid.Row="1" Margin="5"> </TextBox>
        <TextBlock Text="Sample Text 1" Grid.Row="2" Foreground="White" Margin="2"></TextBlock>
        <TextBox Grid.Row="3" Margin="5"></TextBox>
        <Ellipse Fill="Red" Height="100" Width="100" Grid.Row="4" Margin="0,10,0,0"></Ellipse>
        <Button Grid.Row="5" Height="25" Content="Event added at Runtime" x:Name="btnTest"></Button>
    </Grid>
    </Border>

Button ButtoninXAML;

    private void Button_Click(object sender, RoutedEventArgs e)
    {

        StreamReader mysr = new StreamReader(@"D:\Tempwin.xml");
        FrameworkElement  rootObject = XamlReader.Load(mysr.BaseStream) as FrameworkElement;
        ButtoninXAML = LogicalTreeHelper.FindLogicalNode(rootObject, "btnTest") as Button;
        ButtoninXAML.Click += new RoutedEventHandler(Button_Click1); 

        content.Children.Add(rootObject);

    }
    private void Button_Click1(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Added At Runtime");
    }

7
您可以通过以下方式动态显示Xaml:
    string text = @"<TextBlock Text='test' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' />";

    // Convert to stream
    // You can also just stream the xaml from a file, using a FileStream
    MemoryStream stream = new MemoryStream(ASCIIEncoding.UTF8.GetBytes(text));

    // Convert to object
    TextBlock block = (TextBlock)System.Windows.Markup.XamlReader.Load(stream);

    //... now you can put that TextBlock somewhere, for example in your main Window

请查看XamlReader类的详细信息: http://msdn.microsoft.com/zh-cn/library/ms613427%28v=VS.95%29.aspx

你可以使用 XamlReader.Parse 直接解析字符串,而不需要创建一个 MemoryStream。 - Bip901

2

我已经成功在运行时加载了XAML,以下是一个简短的示例:

Grid grd = new Grid();
var grdEncoding = new ASCIIEncoding();
var grdBytes = grdEncoding.GetBytes(myXAML);
grd = (Grid)XamlReader.Load(new MemoryStream(grdBytes));
Grid.SetColumn(grd, 0);
Grid.SetRow(grd, 0);
parentGrid.Children.Add(grd);

private String myXAML = @" <Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Margin='30 10 30 65' VerticalAlignment='Bottom'>" +
                "<Label Content='Date: 1-Feb-2013' FontFamily='Arial' FontSize='12' Foreground='#666666' HorizontalAlignment='Left'/>" +
                "<Label Content='4'  FontFamily='Arial' FontSize='12' Foreground='#666666' HorizontalAlignment='Center'/>" +
                "<Label Content='Hello World'  FontFamily='Arial' FontSize='12' Foreground='#666666' HorizontalAlignment='Right'/>" +
            "</Grid>";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接