Set property system windows resourcedictionary source threw an exception

Hi,
  • Hi,

    >>Can’t we use .xaml file as resourceDictionary ?

    Yes, we can, but the important thing is that ResourceDictionary can only support Brush, Style, Template etc.

    e.g.

    Dictionary1.xaml:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Style TargetType="{x:Type Button}" x:Key="ButtonStyle">
            <Setter Property="FontWeight" Value="Bold" />
            <Setter Property="Width" Value="100" />
            <Setter Property="Height" Value="50" />
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Cursor" Value="Hand"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ResourceDictionary>

    App.xaml:

    <Application.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="Dictionary1.xaml"></ResourceDictionary>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Application.Resources>

    For your requirement, creating a UserControl will be a good choice:

    MyButton.xaml:

    <UserControl x:Class="WpfResourceDict.MyButton"
                 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="300" d:DesignWidth="300">
        <Grid>
            <Button Height="20" Width="60" Content="UserControl" />
        </Grid>
    </UserControl>

    To use it:

    xmlns:local="clr-namespace:<Your namespace>"
            Title="MainWindow" Height="150" Width="225">
        <Grid>
                <local:MyButton Margin="0,0,0,30" />
        </Grid>


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

    Click
    HERE to participate the survey.

    • Marked as answer by
      Franklin ChenMicrosoft employee
      Tuesday, April 1, 2014 9:47 AM

  • I have created WPF application in Visual Studio 2010 when I run the application in Visual Studio 2017 it generating following error

    Unhandled Exception: System.Windows.Markup.XamlParseException: 'Set property 'System.Windows.ResourceDictionary.Source' threw an exception.' Line number '8' and line position '18'. ---> System.IO.IOException: Cannot locate resource 'resourcedic/maindictionary.xaml'.
    

    Following is the app.xaml file that I am using in the application:-

    <Application x:Class="AttendenceSystem.UI.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="StartWindow.xaml">
        <Application.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="ResourceDicMainDictionary.xaml"/>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Application.Resources>    
    </Application>
    

    Anybody help me to resolve this issue. If you need any further details please let me know.

    asked May 30, 2018 at 14:54

    Anil Bali's user avatar

    Anil BaliAnil Bali

    211 silver badge4 bronze badges

    6

    I had the same issue, I had to add this itemGroup to the .csproj of the project

    <ItemGroup>
        <PackageReference Include="MaterialDesignThemes.Wpf">
        <Version>1.0.1</Version>
        </PackageReference>
        <PackageReference Include="Newtonsoft.Json">
        <Version>12.0.3</Version>
        </PackageReference>
    </ItemGroup>
    

    answered Apr 7, 2021 at 15:09

    N.Pozzi's user avatar

    Hi
    bottom line: I am receiving this error only if used materialdesign wpf for a wpf window inside a class library:

    long story:
    I am working on a dll library where it contains some methods as well as a wpf window. code as shown below:
    Window Xaml Code

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    
    <Grid>
        <materialDesign:Card Padding="32" Margin="16">
            <TextBlock Style="{DynamicResource MaterialDesignTitleTextBlock}">My First Material Design App</TextBlock>
        </materialDesign:Card>
    </Grid>
    

    `
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;

    /// Interaction logic for Window1.xaml
    /// </summary>
    
    
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
    

    }
    `

    The calling class:

    `
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Autodesk.Revit.DB;
    using Autodesk.Revit.UI;
    using Autodesk.Revit.Attributes;

    namespace WpfApplication10
    {
    [Transaction(TransactionMode.Manual)]
    class test1 : IExternalCommand
    {
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
    MainWindow main = new MainWindow();
    main.Show();

            return Result.Succeeded;
        }
    }
    

    }
    `

    as soon as the initialization statement starts and hitting Resource dictionary in the xaml it threw the above mentioned exception.

    but if i tried the same for a wpf application and not a library it works like charm. any clues?

    by the way Well don with this library you all are really fascinating.

    See more:

    Application x:Class="FortySixApplesResourceDictionaryDemo.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 StartupUri="MainWindow.xaml">
        <Application.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="pack://application:,,,/Demo.Common;component/Resource Dictionaries/MacStyledWindow.xaml" />
    
    
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Application.Resources>
    </Application>

    ————

    showing error.


    This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    CodeProject,
    20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
    +1 (416) 849-8900

    Set property threw an exception. #450

    Comments

    mostafa901 commented Jul 15, 2016

    Hi
    bottom line: I am receiving this error only if used materialdesign wpf for a wpf window inside a class library:

    Set property ‘System.Windows.ResourceDictionary.Source’ threw an exception.’ Line number ’14’ and line position ’14’.

    long story:
    I am working on a dll library where it contains some methods as well as a wpf window. code as shown below:
    Window Xaml Code

    My First Material Design App

    `
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;

    The calling class:

    `
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Autodesk.Revit.DB;
    using Autodesk.Revit.UI;
    using Autodesk.Revit.Attributes;

    namespace WpfApplication10
    <
    [Transaction(TransactionMode.Manual)]
    class test1 : IExternalCommand
    <
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    <
    MainWindow main = new MainWindow();
    main.Show();

    as soon as the initialization statement starts and hitting Resource dictionary in the xaml it threw the above mentioned exception.

    but if i tried the same for a wpf application and not a library it works like charm. any clues?

    by the way Well don with this library you all are really fascinating.

    The text was updated successfully, but these errors were encountered:

    Источник

    Set property system windows resourcedictionary source threw an exception

    This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

    Answered by:

    Question

    I am getting the following exception while I am assigning value to «Source» property in ResourceDictionary as MyButton.xaml file (which inherits Button class).

    «ResourceDictionary LoadFrom operation failed with URI ‘MyButton.xaml’.» as innerException.

    I implemented following code.

    Note: I am using Visual Studio 2012 (update 4 is installed).

    Note: App.xaml and MyButton.xaml are in same directory.

    Thanks in advance.

    Answers

    >>Can’t we use .xaml file as resourceDictionary ?

    Yes, we can, but the important thing is that ResourceDictionary can only support Brush, Style, Template etc.

    For your requirement, creating a UserControl will be a good choice:

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by Franklin Chen Microsoft employee Tuesday, April 1, 2014 9:47 AM

    All replies

    Following is the implementation for MyButton.xaml

    That will be the problem. WPF is expecting MyButton.xaml to be a resource dictionary not a xaml definition of a button. There is a good blog post here on what resources are.

    To create a resource dictionary just right click and select add new item the select. Resource Dictionary. You can then either add the button definition (making sure to use x:shared=»false») or preferably define a style for the button.

    Can’t we use .xaml file as resourceDictionary ?

    It will become difficult to convert my code from MyButton.xaml file to ResourceDictionary, because

    1. I need code-behind file for implementing event handlers, properties and methods.

    2. For a ResourceDictionary, we cannot get designer interface like in xaml file.

    This designer is needed because, later I need to develop templates consisting several controls. And it will become quite difficult to manage and align controls by the code.

    Источник

    Set property system windows resourcedictionary source threw an exception

    This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

    Answered by:

    Question

    I am getting the following exception while I am assigning value to «Source» property in ResourceDictionary as MyButton.xaml file (which inherits Button class).

    «ResourceDictionary LoadFrom operation failed with URI ‘MyButton.xaml’.» as innerException.

    I implemented following code.

    Note: I am using Visual Studio 2012 (update 4 is installed).

    Note: App.xaml and MyButton.xaml are in same directory.

    Thanks in advance.

    Answers

    >>Can’t we use .xaml file as resourceDictionary ?

    Yes, we can, but the important thing is that ResourceDictionary can only support Brush, Style, Template etc.

    For your requirement, creating a UserControl will be a good choice:

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by Franklin Chen Microsoft employee Tuesday, April 1, 2014 9:47 AM

    All replies

    Following is the implementation for MyButton.xaml

    That will be the problem. WPF is expecting MyButton.xaml to be a resource dictionary not a xaml definition of a button. There is a good blog post here on what resources are.

    To create a resource dictionary just right click and select add new item the select. Resource Dictionary. You can then either add the button definition (making sure to use x:shared=»false») or preferably define a style for the button.

    Can’t we use .xaml file as resourceDictionary ?

    It will become difficult to convert my code from MyButton.xaml file to ResourceDictionary, because

    1. I need code-behind file for implementing event handlers, properties and methods.

    2. For a ResourceDictionary, we cannot get designer interface like in xaml file.

    This designer is needed because, later I need to develop templates consisting several controls. And it will become quite difficult to manage and align controls by the code.

    Источник

    Set property system windows resourcedictionary source threw an exception

    This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

    Answered by:

    Question

    My colleague has been working on a new WPF app. It’s written using VS 2015, .NET 4.5.2. When we run it from within VS it runs fine. We’re using ClickOnce deployment via TFS Build/Release. After installing the same app via ClickOnce, it doesn’t run at all. In fact, it never even pops up before crashing. It just instantly crashes. The only thing you can see is this in the Event Viewer:

    Exception Info: System.Windows.Markup.XamlParseException
    at System.Windows.Markup.WpfXamlLoader.Load(System.Xaml.XamlReader, System.Xaml.IXamlObjectWriterFactory, Boolean, System.Object, System.Xaml.XamlObjectWriterSettings, System.Uri)
    at System.Windows.Markup.WpfXamlLoader.LoadBaml(System.Xaml.XamlReader, Boolean, System.Object, System.Xaml.Permissions.XamlAccessLevel, System.Uri)
    at System.Windows.Markup.XamlReader.LoadBaml(System.IO.Stream, System.Windows.Markup.ParserContext, System.Object, Boolean)
    at System.Windows.Application.LoadComponent(System.Object, System.Uri)
    at CoreFramework.App.InitializeComponent()
    at CoreFramework.App.Main()

    I tried putting in a MessageBox.Show in the application’s constructor, after the InitializeComponent call. Even that did not show.

    How is this possible? What’s going on? How do we determine what’s run when we can’t even begin to find out where its wrong?

    Answers

    At the entry point when app.xaml is merging resource dictionaries or your mainwindow are loading, a resource dictionary isn’t where it’s expected to be or cannot be read for some reason.

    I’ll just merge this resource dictionary. dead.

    Hope that helps.

    All replies

    At the entry point when app.xaml is merging resource dictionaries or your mainwindow are loading, a resource dictionary isn’t where it’s expected to be or cannot be read for some reason.

    I’ll just merge this resource dictionary. dead.

    Hope that helps.

    Given what you’ve said, I’ve taken a look at the App.xaml. There are 3 resource dictionaries that my colleague is merging into a single resource dictionary. One is one that we’ve written and it is where it should be. The other 2 are related to a third party library (ModernUI). Here is the contents of our App.xaml:

    How do I determine if that FirstFloor.ModernUI is whatever it is supposed to be?

    If it works on your machine but not on the users then the most likely explanation is that you’re not delivering some component of modernui or you’re delivering it to the wrong place.

    Hope that helps.

    This may always be related to the deployment of Application.

    You may have missed some of the resources or dll, image , font, or others needed for the program . so try to check the application Include file .

    In addition, you can try to trap unhandled exceptions at different levels in WPF:

    1. AppDomain.CurrentDomain.UnhandledException From all threads in the AppDomain.
    2. Dispatcher.UnhandledException From a single specific UI dispatcher thread.
    3. Application.Current.DispatcherUnhandledException From the main UI dispatcher thread in your WPF application.
    4. TaskScheduler.UnobservedTaskException from within each AppDomain that uses a task scheduler for asynchronous operations.

    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    I’ve been hacking away at this and not really making a lot of progress. I think I’ve finally got the issue with ModernUI resolved; at least its no longer complaining about that. But now I can no longer run the app from within Visual Studio! Now I’m getting errors like this:

    System.Windows.Markup.XamlParseException occurred
    HResult=-2146233087
    LineNumber=16
    LinePosition=18
    Message=’Set property ‘System.Windows.ResourceDictionary.Source’ threw an exception.’ Line number ’16’ and line position ’18’.
    Source=PresentationFramework
    StackTrace:
    at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
    at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
    at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
    at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
    at CoreFramework.App.InitializeComponent() in D:SrcBEMRCoreFrameworkApp.xaml:line 1
    InnerException:
    HResult=-2146232800
    Message=Cannot locate resource ‘assets/coreframeworkresources.xaml’.
    Source=PresentationFramework

    Notice the inner exception about Assets/CoreFrameworkResources.xaml. I thought I’d look further into that, thinking that maybe I’d have to use a Pack URI syntax instead. So I found this Microsoft Docs document which I used to modify how our customized resource dictionary should be referenced within App.Xaml. So, I changed the App.xaml to now look like this:

    But this change didn’t help, either. Now I’m getting this error:

    Источник

    Код в App.xaml

    <Application x:Class=«APP.App»

    xmlns=«http://schemas.microsoft.com/winfx/2006/xaml/presentation»

    xmlns:x=«http://schemas.microsoft.com/winfx/2006/xaml»

    xmlns:local=«clr-namespace:APP»

    StartupUri=«MainWindow.xaml»>

    <Application.Resources>

    <ResourceDictionary>

    <ResourceDictionary.MergedDictionaries>

    <ResourceDictionary Source=«Data/Theme/Light.xaml»/>

    </ResourceDictionary.MergedDictionaries>

    </ResourceDictionary>

    </Application.Resources>

    Добавил Data/Theme/Light.xaml в ресурсы. Запускаю, и ошибки:

    • Необработанное исключение типа «System.Windows.Markup.XamlParseException» в PresentationFramework.dll
    • «Задание свойства «System.Windows.ResourceDictionary.Source» вызвало исключение.»: номер строки «9» и позиция в строке «18»

    Как исправить?

    Измените StartupUri=»MainWindow.xaml» на StartupUri=»FolderName/MainWindow.xaml»

    Решил мою проблему, когда я переместил MainWindow в папку просмотра

    Это случилось со мной несколько раз — всегда, когда я переместил MainWindow.xaml в другую папку и забыл обновить StartupUri в App.xaml

    Visual Studio каким-то образом переименовала мой MainWindow.xaml в MainWindow(1).xaml, поэтому я снова переименовал его в MainWindow.xaml

    В моем случае мне нужно было использовать синтаксис URI пакета, чтобы установить свойство SrartUpUri моего файла App.xaml, чтобы указать на новое местоположение моего MainWindow.xaml, так как:

    <Application x:Class=«TrafficLights.Controller.App»

    xmlns=«http://schemas.microsoft.com/winfx/2006/xaml/presentation»

    xmlns:x=«http://schemas.microsoft.com/winfx/2006/xaml»

    StartupUri=«pack://application:,,,/View/MainWindow.xaml»>

    Подробнее о URI пакетах здесь:

    http://msdn.microsoft.com/en-us/library/aa970069(v=vs.110).aspx

    <Window.Resources/>

    In the XAML file you are working on add the following code if the Resource.Dictionary is named StylesDictionary.xaml and is located in a root directory called Styles.  The Project name is called MyProjectWPF_GUI.

    Code Snippet

    1.  
    2. <Window.Resources>
    3.     <ResourceDictionary>
    4.         <ResourceDictionary.MergedDictionaries>
    5.             <ResourceDictionary Source=»pack://application:,,,/MYProjectWPF_GUI;component/Styles/StylesDictionary.xaml» />
    6.         </ResourceDictionary.MergedDictionaries>
    7.     </ResourceDictionary>
    8. </Window.Resources>

    Note:

    The Source  = pack://application:,,,/MyProjectWPF_GUI;component/Styles/StylesDictionary.xaml”

    needs to have this “pack” syntax if you have a namespace declaration for “UserControls” like is used in this Window.

    xmlns:local=»clr-namespace:MyProjectWPF_GUI» 

    The error at runtime will be: “Set property ‘System.Windows.ResourceDictionary.Source’ threw an exception.”

    Otherwise if you do not declare a namespace for a “UserControl” then you can call it by

    Source=”/Styles/StylesDictionary.xaml”

    Code Snippet

    1. <Window x:Class=»MobiusWindow»
    2.     xmlns=»http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    3.     xmlns:x=»http://schemas.microsoft.com/winfx/2006/xaml&quot;
    4.     WindowStartupLocation=»CenterOwner»
    5.     ResizeMode=»NoResize»
    6.     Title=»Submit to Mobius» Height=»480″ Width=»647″
    7.       xmlns:local=»clr-namespace:MYProjectWPF_GUI»  
    8.     Name=»MobiusWin»>

    <Resource.Dictionary/>

    The Resource.Dictionary looks like the following.  Its filename is called StylesDictionary.xaml and is under a directory called Styles.

    Code Snippet

    1. <ResourceDictionary xmlns=»http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    2.     xmlns:x=»http://schemas.microsoft.com/winfx/2006/xaml»&gt;
    3.  
    4.     <!– Default Button Style–>
    5.           <Style TargetType=»Button»>
    6.             <Setter Property=»FontWeight» Value=»Bold» />
    7.         </Style>
    8.     
    9.     <!– Default ToolTip tyle–>
    10.         <Style x:Key=»{x:Type ToolTip}« TargetType=»ToolTip»>
    11.             <Setter Property=»OverridesDefaultStyle» Value=»true»/>
    12.             <Setter Property=»HasDropShadow» Value=»True»/>
    13.             <Setter Property=»Template»>
    14.                 <Setter.Value>
    15.                     <ControlTemplate TargetType=»ToolTip»>
    16.                         <Border CornerRadius=»7″ HorizontalAlignment=»Center» VerticalAlignment=»Top» Padding=»5″ BorderThickness=»3,3,3,3″>
    17.                             <Border.Background>
    18.                                 <LinearGradientBrush EndPoint=»0.5,1″ StartPoint=»0.5,0″>
    19.                                     <GradientStop Color=»#CF181818″ Offset=»0″/>
    20.                                     <GradientStop Color=»#BE1C1C1C» Offset=»1″/>
    21.                                 </LinearGradientBrush>
    22.                             </Border.Background>
    23.                             <Border.BorderBrush>
    24.                                 <LinearGradientBrush EndPoint=»0.5,1″ StartPoint=»0.5,0″>
    25.                                     <GradientStop Color=»#80FFFFFF» Offset=»0″/>
    26.                                     <GradientStop Color=»#7FFFFFFF» Offset=»1″/>
    27.                                     <GradientStop Color=»#FFFFF18D» Offset=»0.344″/>
    28.                                     <GradientStop Color=»#FFFFF4AB» Offset=»0.647″/>
    29.                                 </LinearGradientBrush>
    30.                             </Border.BorderBrush>
    31.                             <StackPanel>
    32.                                 <TextBlock FontFamily=»Tahoma» FontSize=»11″ Text=»{TemplateBinding Content}« Foreground=»#FFFFFFFF» />
    33.                             </StackPanel>
    34.                         </Border>
    35.                     </ControlTemplate>
    36.                 </Setter.Value>
    37.             </Setter>
    38.         </Style>
    39. </ResourceDictionary>

    Good Luck

    Tags: Microsoft, Resource.Dictionary, Windows.Resources, WPF, xaml


    This entry was posted on February 28, 2011 at 3:06 am and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed.
    You can leave a response, or trackback from your own site.

    •  
    • wpf

    • resources

    • xaml

    •  04-10-2019
    •  | 

    •  

    Question

    In my WPF project i keep a user control in a separate library project. The user control accesses resources in a separate XAML file, like this:

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Resources/ViewResources.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <!-- Local styles here -->
        </ResourceDictionary>
    </UserControl.Resources>
    

    The resource file, ViewResources.xaml, resides in a folder in the control library project named Resources. It has the default build action (Page) and custom tool (MSBuild:Compile).

    The problem is when I reference the control library in my WPF application and use the user control. At runtime, I get the following XamlParseException:

    Set property 'System.Windows.ResourceDictionary.Source' threw an exception.
    

    …which wraps the IOException:

    Cannot locate resource 'resources/viewresources.xaml'.
    

    How can I fix this? I have tried to change the resource file’s build action to «content» and have it copied to the output directory (that works for files and similar «dumb» resources). But to no avail. Also, it doesn’t work property in the user control then.

    Is there a better way to specify the path?

    Will I have to move the resource file to the application project (I’d rather not, as it belongs in the user control’s domain).

    Solution

    Found it.

    Turns out there is a better way to specify the path, Pack URIs. I changed the XAML to the following:

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/RoutingManager;component/Resources/ViewResources.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <!-- Local styles here -->
        </ResourceDictionary>
    </UserControl.Resources>
    

    and that fixed it.

    OTHER TIPS

    I thought it was worth posting this just in case anyone else is struggling with the same problem, as I’ve spent over two hours fighting with syntax, etc. only to find that the solution was dead simple, but not that apparent:
    When referencing a packed resource from another control library, it seems to work fine at design time, and even compiles without error, but fails at runtime with the ‘Set property ‘System.Windows.ResourceDictionary.Source’ threw an exception’ error. It turns out that simply referencing the resource assembly from your control library is not enough, you ALSO need to add a REFERENCE to the assembly containing the resource dictionary in you main application assembly, else it seems it does not get compiled into the application. (i.e. Startup Application (the one with app.xaml) -> Add Reference -> select assembly with referenced resource file/s).

    Hope this helps!

    In my case I had the ResourceDictionary and the UserControl on the same Library, but separate from the main application. What worked for me was specifying the name of the assembly in the format Adam suggested in the comment AND I had to change the ResourceDictionary in the project from Embedded Resource to Page. I didn’t try using the pack:// format, but I assume it would work too.

    <ResourceDictionary Source="/AssemblyName;component/Assets/MyResource.xaml"/>
    

    I had the same error (IOException — file not found), which cost me a day of my life that I’ll never get back.

    Using neither the simpler «/assemblyname…» nor the «pack://….» syntax worked for me.

    I was referencing the resource assembly in my main assembly correctly.

    The error disappeared when I changed my xaml resource file Build Action property to «Resource», as mentioned above.

    However, I then encountered a XamlParseException at this line:

    <ImageBrush x:Key="WindowBackground" ImageSource="Images/gradient.png" />

    (which I had hand-typed).

    This left the xaml resource file I was trying to include with effectively an invalid dependency.

    Oddly the fix was to delete the ImageSource property I had typed, re-insert it BUT select the image from the pulldown menus that appear as a result.

    Even though the resulting line appears exactly the same, it clearly isn’t.

    Starting to dislike WPF (VS2013), but hope this helps.

    :0/

    I had the same situation, but the Pack URIs didn’t help me, I was still getting «Cannot locate resource…» exception in the referencing (executable) project. What helped me, was the setting of my ResourceDictionary files in the custom control library project as Embedded Resource.

    When you click on the integrated RWS AppStore in Studio > Add-Ins, Studio crashes with the following error message:

    Set property ‘System.Windows.ResourceDictionary.Source’ threw an exception.

    User-added image

    1. Go to: C:Users%USERNAME%AppDataRoamingSDLSDL Trados Studio16PluginsPackages 

                          ​​​​​​​C:Users%USERNAME%AppDataRoamingSDLSDL Trados Studio16PluginsUnpacked
                          C:Users%USERNAME%AppDataLocalSDLSDL Trados Studio16PluginsPackages 
                          C:Users%USERNAME%AppDataLocalSDLSDL Trados Studio16PluginsUnpacked

                If you don’t find it there please check also C:ProgramDataSDLSDL Trados Studio16PluginsUnpacked 
    ​​​​​​​                                                                               C:ProgramDataSDLSDL Trados Studio16PluginsPackages

          2. Check for the MT Comparison.sdlplugin,  applyTM Template.sdlplugin or LingotekTMS.sdlplugin

          3. Delete the plugin(s)

          4. Open Trados Studio and install the plugin(s) from the integrated AppStore
           Integrated RWS Appstore should be accessible from Trados Studio

    Note: If you can’t find the path above, open Windows File Explorer, click on View and check «Hidden Items» checkbox.

    Mismatch between Trados Studio 2021 SR2 and outdated versions of MT Comparison.sdlplugin, applyTM Template.sdlplugin or LingotekTMS.sdlplugin

    In general this issue is caused when a referenced resource cannot be found.

    <Application x:Class="AppName.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 StartupUri="MainWindow.xaml">
        <Application.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Application.Resources>
    </Application>
    

    In my specific circumstance, as the xaml above details, this issue was caused by a reference to PresentationFramework.Aero DLL that was not contained in the output bin folder of the compiled project. Under references, setting Copy Local to true did the trick for me.

    References
    http://stackoverflow.com/questions/3747972/wpf-usercontrol-cannot-find-xaml-resource-in-referencing-project

    About Ronnie Diaz

    Ronnie Diaz is a software engineer and tech consultant. Ronnie started his career in front-end and back-end development for companies in ecommerce, service industries and remote education. This work transitioned from traditional desktop client-server applications through early cloud development. Software included human resource management and service technician workflows, online retail e-commerce and electronic ordering and fulfillment, IVR customer relational systems, and video streaming remote learning SCORM web applications. Hands on server experience and software performance optimization led to creation of a startup business focused on collocated data center services and continued experience with video streaming hardware and software. This led to a career in Amazon Prime Video where Ronnie is currently employed, building software and systems which stream live sports and events for millions of viewers around the world.

    Понравилась статья? Поделить с друзьями:
  • Set java home windows 10 from cmd
  • Set java home variable windows 10
  • Set executionpolicy windows powershell updated your execution policy successfully
  • Set environment variable windows 10 cmd
  • Session1 initialization failed windows 10 решение проблемы