gpt4 book ai didi

c# - 使用样式以编程方式创建按钮

转载 作者:行者123 更新时间:2023-12-02 21:43:19 26 4
gpt4 key购买 nike

简单的语法问题。在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 的分层资源查找帮助器方法。

然而,在互联网上快速搜索放弃了this article它描述了您可以使用的一个很好的扩展方法:

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");

关于c# - 使用样式以编程方式创建按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19989912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com