2

Simple syntax question. Programming silverlight 4 on VS2010. I created a button style in xaml:

<UserControl.Resources>
    <Style x:Key ="TestbuttonStyle" TargetType="Button">
        <Setter Property="Width" Value="150"></Setter>
        <Setter Property="Margin" Value="0,0,0,10"></Setter>
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
                        <Image Source="http://i40.tinypic.com/j5k1kw.jpg" Height="20" Width="20"  Margin="-30,0,0,0"></Image>
                        <TextBlock Text="sampleuser&#13;sample number" Margin="5,0,0,0"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>

I need to create a button in the code behind, but using this style. I tried doign something like this:

        Button btn = new Button();
        //btn.Style = {TestbuttonStyle};  -what do i put  here?
        grid.children.add(btn);

how to I apply the style and add to my usercontrol grid?

1 Answer 1

5

Initially I thought you were working with WPF. Then I realized it's about Silverlight which doesn't have a hierarchical resource look-up helper method similar to WPF's FindResource or TryFindResource, respectively.

However, a quick search on the internet gave up this article which describes a nice extension method you can use:

public static object TryFindResource(this FrameworkElement element, object resourceKey)
{
    var currentElement = element;

    while (currentElement != null)
    {
        var resource = currentElement.Resources[resourceKey];
        if (resource != null)
        {
            return resource;
        }

        currentElement = currentElement.Parent as FrameworkElement;
    }

    return Application.Current.Resources[resourceKey];
}

Then you can use it like this:

btn.Style = (Style)this.TryFindResource("TestbuttonStyle");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.