c# - WPF-C# : This element is not currently associated with any context

标签 c# .net wpf resourcedictionary elementhost

我有一个 WPF 用户控件,我在 ElementHostControl 内的 WinForms 控件中使用它。然后我启动一个 WPF 窗口,同时 Windows 窗体仍处于打开状态。如果我随后关闭 WPF 窗口,并尝试向我的 WPF UserControl 添加一个子元素,它会在“InitializeComponent()”(子元素的)处崩溃,但以下情况除外:

"A first chance exception of type 'System.Configuration.ConfigurationErrorsException' occurred in System.Configuration.dll. Additional information: This element is not currently associated with any context"

我找到了为什么会这样,但我不知道如何解决这个问题。如果我省略这段代码:

public static void EnsureApplicationResources()
    {
        if (Application.Current == null)
        {
            // create the Application object
            new Application();
            string assemblyName = System.IO.Path.GetFileNameWithoutExtension(
                Assembly.GetExecutingAssembly().ManifestModule.Name);

            // merge in your application resources
            Application.Current.Resources.MergedDictionaries.Add(
                Application.LoadComponent(new Uri("/KolonistenClient;component/KolonistenResourceDictionary.xaml", UriKind.RelativeOrAbsolute))
                as ResourceDictionary);
        }
    }

然后一切都很好。不过,我需要它,因为我的 ResourceDictionary(以及我定义的样式和模板)在整个 WPF 窗口和控件中都不可用。 This I found out about here

有什么方法可以结合两全其美吗?保留我的 ResourceDictionary,同时防止应用程序崩溃?

最佳答案

我最终通过 xaml 在每个窗口中手动添加 ResourceDictionary 解决了这个问题。这样,我的 WinForms 中的 UserControl 就不会受到影响。

不幸的是,仍然不明白 为什么 它崩溃了。

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/KolonistenClient;component/KolonistenResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

关于c# - WPF-C# : This element is not currently associated with any context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2073497/

相关文章:

c# - 带复选按钮组的工具条

.net - 如何创建包含集合集合的配置节?

WPF 在 mediaElement 上双击进入全屏并不总是有反应

c# - 在 EF Core 2.1 中的 DbContext 上执行 RAW SQL

c# - WPF 项模板 - TabControl

c# - 泛型的乐趣 : no implicit reference conversion error

c# - 设置UIaccess更改ShowDialog的行为

c# - WPF:如何使自定义模式对话框闪烁?

c# - 在 C# 中,如何查看帐户中的第一个字符是否为特定值?

c# - 之间的Linq性能