繁体   English   中英

以编程方式创建带有样式的按钮

[英]create a button programmatically with styles

简单的语法问题。 在VS2010上编程silverlight 4。 我在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>

我需要在后面的代码中创建一个按钮,但要使用这种样式。 我试图统治这样的事情:

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

如何应用样式并添加到用户控件网格中?

最初,我以为您正在使用WPF。 然后我意识到这是关于Silverlight的,它没有类似于WPF的FindResource或TryFindResource的分层资源查找帮助器方法。

但是,在Internet上进行了快速搜索就放弃了这篇文章该文章描述了可以使用的不错的扩展方法:

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];
}

然后,您可以像这样使用它:

btn.Style = (Style)this.TryFindResource("TestbuttonStyle");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM