我需要加载并使用 XAML 文件。

我写了简单的 XAML 文件:

<Window      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="150" d:DesignWidth="300" Title="My Window">
    <x:Code>
        <![CDATA[
            void btnMyButton_Click_1(object sender, RoutedEventArgs e) {
                MessageBox.Show("Hello world", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        ]]>
    </x:Code>
    <Grid>
        <Button x:Name="btnMyButton" x:FieldModifier="public" Margin="10" Padding="10"
                FontSize="20" Click="btnMyButton_Click_1">My button</Button>
    </Grid>
</Window>

然后我尝试在我的代码中加载这个 XAML:
String curDir = io.Path.GetDirectoryName(typeof(Lisp_Wpf.Commands).Assembly.Location);
String xamlFileName = "MyWindow.xaml";
String fileFullName = io.Path.Combine(curDir, xamlFileName);
DependencyObject depObj = default(DependencyObject);
using (io.FileStream fs = new io.FileStream(fileFullName, io.FileMode.Open)) {
    depObj = XamlReader.Load(fs) as DependencyObject;
    fs.Close();
}
if (depObj != null && depObj is Window) {
    Window win = (Window)depObj;
    acad.ShowModalWindow(win);
}

但我得到了异常(exception):



我找到了这样的信息 here :



但是如果我在我的 Window 元素中添加 x:Class 属性:
x:Class="Lisp_Wpf.MainWindow"

然后我得到异常:



在我的 MS Visual Studio 项目中,XML 文件具有以下属性:
构建操作 = 无;
复制到输出目录 = 始终复制;
自定义工具 = (空字符串);

我删除了此 XAML 的部分 CS 文件。

最佳答案

如果你想在运行时加载 xaml,你不能在你的 XAML 文件后面提供任何代码。可能你可以只为按钮单击附加一般事件并在运行时识别控件 - 只需查看下面的链接并尝试一下。

Loading XAML XML through runtime?

关于c# - WPF:加载 XAML 文件,其中包含 x:Code 元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13747822/

10-11 22:05
查看更多