Cannot instantiate UserControl from another assembly - Resource cannot be found

吃可爱长大的小学妹 提交于 2019-12-12 02:26:27

问题


I have a solution with two WPF projects: Primary and Secondary.

In the Primary project, a Window named PrimaryView instantiates an UserControl called SecondaryControl, defined in Secondary project.

SecondaryControl uses SecondaryStyle, which is defined in SecondaryResourceDictionary (as you might have guessed already, defined in SecondaryProject).

The fact is: when I try to run the solution, I get a XamlParseError, and digging InnerExceptions I eventually find the culprit, the ResourceNotFound error.

So my questions are:

  • If SecondaryControl and its SecondaryStyle are defined in the same assembly, why can't I instantiate it it PrimaryAssembly?

  • Should I make SecondaryStyle available to PrimaryProject namespace somehow? Why?


回答1:


I try to help you by explanation how it works in my projects. A separate assembly contains a common control and common resource dictionary like this:

CommonResources.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <!--  Some resources  --> 

</ResourceDictionary>

SomeCommonControl.xaml

<UserControl x:Class="YourAssembly.SomeCommonControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/CommonResources.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

    <!-- Some specific content -->

</UserControl>

I can use this control and resources from another assemblies and WPF-projects like this:

<Window x:Class="YourWPFProject.SomeWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:common="clr-namespace:YourAssembly">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/CommonResources.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

    <common:SomeCommonControl />

</Window>

I hope this will help you.



来源:https://stackoverflow.com/questions/32950097/cannot-instantiate-usercontrol-from-another-assembly-resource-cannot-be-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!