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?
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}}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With