コードビハインドから 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);
}
...
コードは、その目的が自明であるほど単純であると思います。
要するに、拡張メソッドのアプローチの何が問題なのですか? Google と SO 自体をブラウジングすると、両方の方法が機能するように思えます。
何が欠けていますか?