我正在尝试从后面的代码中检索 Application.Resources 元素,我很困惑,因为通过扩展方法这样做似乎不起作用,另一方面,使完全相同的方法成为“正常”的方法成功。
让我指出,这几乎完全针对 Silverlight 开发中的自我培训。
我想要实现的是通过代码隐藏从 XAML中检索Style
泛型的(定义为资源) 。TextBlock
这是属性(它在里面定义App.xaml
)
<Application.Resources>
<Style x:Key="contentTextStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="White" />
</Style>
[...]
如您所见,这是一个简单的“将我的文本块涂成白色”属性。
这是一个“正常”的方法:
public static class ApplicationResources
{
public static T RetrieveStaticResource<T>(string resourceKey) where T : class
{
if(Application.Current.Resources.Contains(resourceKey))
return Application.Current.Resources[resourceKey] as T;
else
return null;
}
...
这是扩展方法形式的代码:
public static class ApplicationResources
{
public static void RetrieveStaticResourceExt<T>(this T obj, string resourceKey) where T : class
{
if(Application.Current.Resources.Contains(resourceKey))
obj = Application.Current.Resources[resourceKey] as T;
else
obj = null;
}
...
这是上述方法的调用者(注意这是一个不同的类,但都存在于同一个命名空间中):
public static class UIElementsGenerator
{
/// <summary>
/// Appends a TextBlock to 'container', name and text can be provided (they should be, if this is used more than once...)
/// </summary>
public static void AddTextBlock(this StackPanel container, string controlName = "newTextBlock", string text = "")
{
TextBlock ret = new TextBlock();
ret.Text = controlName + ": " + text;
ret.TextWrapping = TextWrapping.Wrap;
//This uses the 1st non-extension method, this **WORKS** (textblock turns out white)
ret.Style = MyHelper.RetrieveStaticResource<Style>("contentTextStyle");
//This uses the 2nd one, and **DOESN'T WORK** (textbox stays black)
ret.Style.RetrieveStaticResourceExt<Style>("contentTextStyle");
container.Children.Add(ret);
}
...
我认为代码很简单,其目的是不言自明的。
言归正传,扩展方法有什么问题?浏览谷歌和 SO 本身,在我看来这两种方法都应该有效。
我错过了什么?