Reputation: 21
How do I access the contents in a resource dictionary using C#?
For example, here is my code in XAML:
<system:String x:Key="NewGroup">New Group Name</system:String>
And I want to access it here in C#:
private void OnAddGroup(object sender, ExecutedRoutedEventArgs e)
{
BooksGroupInfo group = new BooksGroupInfo();
group.GroupName = "New Group" + TheTabControl.Items.Count;
TabItem tab = AddGroup(group);
_currentLibrary.addGroup(group);
_currentLibrary.CurrentGroup = group;
}
Instead of typing "New Group" in C#, I would like to replace that and have access in the resource dictionary in XAML. So the command will automatically get the Name that is in the resource dictionary.
I've tried a couple of solutions like:
(System.String)this.FindResource("NewGroup");
Application.Current.Resources[typeof(System.String)];
and so on... but they do not seem to work.
I am doing a Localization using locbaml and it doesn't parse the Text/Name on C# (or I don't know how to) and that was the only solution I thought was possible.
Upvotes: 2
Views: 2433
Reputation: 2994
If you cannot guarantee the existence of your resources then using
FrameworkElement.TryFindResource
will be a better solution. It is similar to FindResource
but rather than throwing an exception, TryFindResource
returns null
if no resource with the provided key is found. (Implementation of TryXxx()
methods is called TryGet Pattern.) Sample in XAML code-behind:
button.Content = this.TryFindResource("NewGroup");
Upvotes: 0
Reputation: 49619
Usually using FrameworkElement.FindResource like this: string s = this.FindResource("NewGroup") as string;
works. It is more likely that the resource with the key "NewGroup" does not exist in the scope of your control or window (whatever this
is). You must make sure that the resource is there. E.g. if your resource comes from another file you have to use MergedDictionaries. You can test if the resource is actually acessible try to acess it from XAML that belongs to your codebehind where OnAddGroup
is definde.
I hope that makes sense.
Upvotes: 5