gpt4 book ai didi

.net - 我可以在代码隐藏中获取样式的键吗? (WPF)

转载 作者:行者123 更新时间:2023-12-04 00:51:29 24 4
gpt4 key购买 nike

如果我有以下代码:

Style defaultStyle = (Style)FindResource("MyTestStyle");

有没有办法获得样式的名称(即反向查找)?类似的东西:
string name = defaultStyle.SomeMagicLookUpFunction()

其中 name 将评估为“MyTestStyle”。

这可能吗?

最佳答案

我创建了一个小的帮助器类,它使用一个方法来执行您需要的反向查找。

public static class ResourceHelper
{
static public string FindNameFromResource(ResourceDictionary dictionary, object resourceItem)
{
foreach (object key in dictionary.Keys)
{
if (dictionary[key] == resourceItem)
{
return key.ToString();
}
}

return null;
}
}

您可以使用以下方法调用它
string name = ResourceHelper.FindNameFromResource(this.Resources, defaultStyle);

FrameworkElement有自己的 .Resources字典,使用 'this' 假定您处于定义 MyTestStyle 的正确位置。如果需要,您可以向静态类添加更多方法以递归遍历窗口中的所有字典(应用程序?)

关于.net - 我可以在代码隐藏中获取样式的键吗? (WPF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/538750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com