3

我在部署 WPF 项目时遇到问题,部署的项目在启动时崩溃并在第 4 行位置 70 处产生内部异常“不能在同一实例上嵌套 BeginInit 调用”的 XAML.Parse.Exception。应用程序在我的计算机上具有完全权限。我问这个问题是因为关于这个问题的几个问题并没有真正解决这个问题。

这是它在前几行中引用的 XAML 代码。

<Window
    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" mc:Ignorable="d" x:Class="ASRV.MainWindow"
    Title="ASRV GUI" Height="768" Width="1024" ResizeMode="CanMinimize">
<Window.Resources>
</Window.Resources>
<Window.Background>
    <ImageBrush ImageSource="pack://siteoforigin:,,,/background.png"/>
</Window.Background>
4

2 回答 2

4

我的猜测是:

<Window.Background>
    <ImageBrush ImageSource="pack://siteoforigin:,,,/background.png"/>
</Window.Background>

您可能会在同一窗口或子控件的其他地方重用此图像。

BeginInit 在数据绑定中被调用,这是我在您的示例代码中可以看到的唯一数据绑定内容。“BeginInit 调用同一个实例”指向它被绑定了两次。

于 2013-05-23T01:39:34.460 回答
1

正如@basarat 在他的回答中所说,每当尝试绑定对象两次时都会遇到此错误。除了在 OP 中看到的示例之外,我还遇到了在我的案例中通过在 CodeBehind 和 xaml 中设置 DataContext 导致的相同错误:

在 MainWindow.xaml 文件中,我有以下内容:

<Window xmlns:vm="clr-namespace:MyApp.ViewModel"
    [...more xmlns references skipped for brevity...]
    <!--the next three lines caused a problem, when combined with the code behind-->
    <Window.DataContext>
        <vm:MainViewModel/>
    </Window.DataContext>
</Window>

在 MainWindow.xaml.cs 文件中,我有这个:

namespace MyApp.View
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainViewModel MainViewModel { get; set; }
        public MainWindow()
        {
            bool success = false;
            MainViewModel = new MainViewModel();
            // This line caused the problem in combination with the xaml above
            DataContext = MainViewModel;
            InitializeComponent();
        }
    }
}

为了摆脱这个问题,我删除了一个 DataContext 设置器;它适用于 xaml 中设置的数据上下文后面代码中设置的数据 cantext,而不是两者

PS我添加这个答案是因为这是搜索这个问题的第一个答案,我觉得进一步的解释会对其他访问者有用。

于 2020-05-14T11:00:06.413 回答