简单的语法问题。在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 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);
如何应用样式并添加到我的usercontrol网格?
答案 0 :(得分:5)
最初我以为你在使用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");