ful*_*per 2 c# silverlight xaml
简单的语法问题.在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>
Run Code Online (Sandbox Code Playgroud)
我需要在后面的代码中创建一个按钮,但使用这种风格.我尝试过像这样的东西:
Button btn = new Button();
//btn.Style = {TestbuttonStyle}; -what do i put here?
grid.children.add(btn);
Run Code Online (Sandbox Code Playgroud)
如何应用样式并添加到我的usercontrol网格?
最初我以为你在使用WPF.然后我意识到它是关于Silverlight的,它没有分别类似于WPF的FindResource或TryFindResource的分层资源查找辅助方法.
但是,在互联网上快速搜索放弃了这篇文章,它描述了一个很好的扩展方法,你可以使用:
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];
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
btn.Style = (Style)this.TryFindResource("TestbuttonStyle");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1107 次 |
| 最近记录: |