Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define x:Key for resource in one place and use it in XAML and code behind

Question in title pretty much sums it up. I have some resource object defined in XAML and I'd like to access it in code behind also. So is there a way to define x:Key for it at one place instead of hard coding x:Key (as string) in both XAML and code behind?

like image 389
matori82 Avatar asked Dec 21 '22 20:12

matori82


1 Answers

If you want to not have to code up the string twice you can store it as a static variable, here I've put it in App.cs

public partial class App : Application
{
    public static string Key1 = "testKey";
}

When you want to use this key in a resource for your app you can do so like this.

<Application.Resources>        
   <SolidColorBrush x:Key="{x:Static local:App.Key1}"/>
</Application.Resources>

And in C# you no longer need to use the exact string name because it's in App

var brush = FindResource(App.Key1);

To use the resource in XAML you use

<TextBox Background="{StaticResource {x:Static local:App.Key1}}" 
like image 160
Andy Avatar answered May 28 '23 02:05

Andy