tags:

views:

101

answers:

2

Hi. I do not know how to use a defined Application Style Resource in code. I have defined:

<Application.Resources> <Style x:Key="OrangeButton" TargetType="{x:Type Button}">

I am using this resource in the XAML section of my application like:

<Button Name="Button_Start" style="{StaticResource OrangeButton}" Margin="0">

and it is working fine, and I can also change the Button Style by code

Button_Start.Style = CType(FindResource("RedButton"), Style)

but only in the VB file that was automatically created when I created my new project. If I add a new class file and try do the same it says:

Name 'FindResource' is not declared

My problem is therefore, how to make use of Application resources in all the different class files in my application.

Peter

+2  A: 

The FindResource method is defined by the FrameworkElement class, so it will only be available if your class extends that or you have an instance of FrameworkElement from which to start your resource lookup.

However, if you know your resource resides at the Application level, you can use either TryFindResource or Resources as follows (C#, but should be easy to infer the VB):

object resource;

if (Application.Current.TryFindResource("RedButton", out resource))
{
    Style indirectStyle = (Style)resource;
}

//or use this
Style directStyle = Applications.Current.Resources["RedButton"] as Style;

HTH, Kent

Kent Boogaart
A: 

Hi Kent Thank you for the answer, I am not sure I understand all you are writing, but I have it to work now with the code

    MyButton.Style = CType(Application.Current.Resources("GreenButton"), Style)

Very nice. Peter