views:

580

answers:

1

Hello! 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 doesnt parse the Text/Name on C# (or i dont know how to) and that was the only solution i thought was possible. Can anyone please help me?! THANKS ALOT!

+2  A: 

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.

bitbonk
hello.. thank you for the reply but i still cant get it to work. Sorry kinda new at this..
JB
I added this on the code and it is not accepting the 4th line.. i dont know if i did it correctly, just added the source of the resource dictionary..
JB
ResourceDictionary resourceDictionary = sender as ResourceDictionary; resourceDictionary.Source = new Uri("Source.xaml", UriKind.Relative); BooksGroupInfo group = new BooksGroupInfo(); group.GroupName = (string resourceDictionary = this.FindResource("NewGroup") as string) + TheTabControl.Items.Count; TabItem tab = AddGroup(group); _currentLibrary.addGroup(group); _currentLibrary.CurrentGroup = group;
JB
group.GroupName = (this.FindResource("NewGroup") as string) + TheTabControl.Items.Count;
bitbonk
I don't think you need this: ResourceDictionary resourceDictionary = sender as ResourceDictionary; resourceDictionary.Source = new Uri("Source.xaml", UriKind.Relative);
bitbonk
The resource dictionary must be added to the resource section of your main XAML using mergeddictionaries
bitbonk