从Brush中检索x:Name或x:Key

时间:2012-11-20 16:15:55

标签: c# wpf xaml

XAML:

<ResourceDictionary> 
    <SolidColorBrush x:Name="MyBrush1" x:Key="MyBrush1" Color="Red" />
</ResourceDictionary>

C#:

brush = userControl.FindResource("MyBrush1")

如何从画笔中检索x:名称或x:键?是否可以通过执行以下操作来检索它们:

brush.Name

brush.Key

1 个答案:

答案 0 :(得分:4)

public static class ResourceHelper
{
    public static string FindNameFromResource(ResourceDictionary dictionary, 
           object resourceItem)
    {
        return (dictionary.Contains(resourceItem)) ? 
               dictionary[resourceItem].ToString() : 
               string.Empty;
    }
}

helper类用单个方法进行反向查找

您可以这样称呼它:

string name = ResourceHelper.FindNameFromResource(this.Resources, defaultStyle);