0

我正在尝试从后面的代码中检索 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 本身,在我看来这两种方法都应该有效。

我错过了什么?

4

2 回答 2

1

试试这个

 public static void ApplyStyleResourceExt<T>(this T obj, string resourceKey) where T : FrameworkElement
        {
            if (Application.Current.Resources.Contains(resourceKey))
                obj.Style  = Application.Current.Resources[resourceKey] as Style;
            else
                obj.Style = null;
        }

像这样使用:

ret.ApplyStyleResourceExt("contentTextStyle");
于 2012-03-08T09:02:27.913 回答
1

正如我在对该主题进行更多研究后发现的那样,我想做的事情(拿起任何东西并将其放在任何地方)无法通过扩展方法完成,因为如果它是值类型(它们提供的功能范式倾向于不变性,或者我被告知)。

这是我想出的,看起来我不会再靠近了:

public static T GetStaticResource<T>(string resourceKey) where T : class
        {
            if (Application.Current.Resources.Contains(resourceKey))
                return Application.Current.Resources[resourceKey] as T;
            else
                return null;
        }
于 2012-03-08T10:04:38.263 回答