Ryan Gan
Ryan Gan

Reputation: 11

How to add ResourceDictionary programmatically?

I'm new in C# WPF and only can rely on the internet to proceed my project. Currently, I have an issue on adding a ResourceDictionary name ThumbStyle.xaml that holds a few styles which needed to access in a class file named LineAdorner.cs.

Code from ThumbStyle.xaml:

<Style x:Key="LineMoveThumbStyle" TargetType="{x:Type Thumb}">
    <Setter Property="Cursor" Value="SizeAll"></Setter>
    <Setter Property="Width" Value="7"></Setter>
    <Setter Property="Height" Value="7"></Setter>
</Style>

<Style x:Key="LineResizeThumbStyle" TargetType="{x:Type Thumb}">
    <Setter Property="Width" Value="7"></Setter>
    <Setter Property="Height" Value="7"></Setter>
    <Setter Property="Cursor" Value="Hand"></Setter>
</Style> 

Code from LineAdorner.cs:

this._moveThumb = new MoveThumb();
this._moveThumb.Style = (Style)Application.Current.FindResource("LineMoveThumbStyle");
this._visuals.Add(this._moveThumb);

this._startThumb = new LineStartPointThumb(_adornedLine);
this._startThumb.Style = (Style)Application.Current.FindResource("LineResizeThumbStyle");
this._visuals.Add(this._startThumb);

this._endThumb = new LineEndPointThumb(_adornedLine);
this._endThumb.Style = (Style)Application.Current.FindResource("LineResizeThumbStyle");
this._visuals.Add(this._endThumb);

As seen from above, I was attempted to use the "FindResource" method to retrieve the style from Thumbsytle.xaml into LineAdorner.cs. Yet The system throw me an error:

System.Windows.ResourceReferenceKeyNotFoundException occurred.
Message='LineMoveThumbStyle' resource not found.

Are there some steps I'm missing? Hope that anyone can help me out with this problem. Thank you very much.

Upvotes: 1

Views: 4638

Answers (2)

Logikoz
Logikoz

Reputation: 61

Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary
{
Source = new Uri("/DLLName;component/subFolder/dictionary.xaml", UriKind.RelativeOrAbsolute)
});

Upvotes: 4

Petar Stojanovski
Petar Stojanovski

Reputation: 88

I don't quite get what you are trying to do, but will this help you? First, put your resource in a folder name Resources and then:

            var rsrc = "Resources/ThumbStyle.xaml";
            var currentRsrc = new Uri(rsrc, UriKind.RelativeOrAbsolute);
            Application.Current.Resources.MergedDictionaries[0] = new ResourceDictionary() { Source = currentRsrc };

Good luck!

Upvotes: 1

Related Questions