WPF: access to resources in the control assembly

I have a control for which I want to declare resources in an xaml file. if it was a user control, I could place resources in a block <UserControl.Resources>and reference them in code through this.Resources["myResourceKey"]how I can achieve the same functionality in the control. at the moment, the only link to xaml I have is through the static constructor of the controls, referring to the style (and control pattern)

static SlimlineSimpleFieldTextBlock() {
         DefaultStyleKeyProperty.OverrideMetadata(typeof(SlimlineSimpleFieldTextBlock), new FrameworkPropertyMetadata(typeof(SlimlineSimpleFieldTextBlock)));
}

but even if I add a block to xaml <Style.Resources>, I can’t refer to them (since the style is null at the OnApplyTemplate stage), and even if I did, it would mean that if someone eles override the style, lose resources.

+3
source share
1 answer

Create your resource key with ComponentResourceKey. Regular resource keys are searched only for the visual tree and application resources. But any resource key that is ComponentResourceKeyalso executed in the theme dictionary for the assembly containing this type. (This is also true for Typeobjects used as resource keys.)

In your /Generic.xaml themes of an assembly containing a control called Sandwich, you can:

<SolidColorBrush x:Key="{ComponentResourceKey local:Sandwich, Lettuce}"
                 Color="#00FF00" />

<ControlTemplate x:Key="{ComponentResourceKey local:Sandwich, PeanutButter}" ...>
  ...
</ControlTemplate>

You can reference these resources in code as follows:

var lettuce = (Brush)FindResource(
                 new ComponentResourceKey(typeof(Sandwich), "Lettuce"));

var penutButter = (ControlTemplate)FindResource(
                 new ComponentResourceKey(typeof(Sandwich), "PeanutButter"));

You can also reference these resources in XAML as follows:

<Border Background="{StaticResource ResourceKey={ComponentResourceKey local:Sandwich, Lettuce}}" />

, FindResource, XAML , FrameworkElement, FrameworkContentElement Application.

ComponentResourceKey , , . , ComponentResourceKey {ComponentResourceKey local:Sandwich,Seasonings}, Soup Sandwich . ComponentResourceKey , , , .

, URI ResourceDictionary , . Themes/Generic.xaml, , .

, Themes/Generic.xaml, ThemeInfoAttribute . AssemblyInfo.cs:

[assembly:ThemeInfoAttribute(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
+5

Source: https://habr.com/ru/post/1751328/


All Articles