Skip to main content
 首页 » 编程设计

c#之Application.Current.Resources 和 Resources 之间有什么区别

2024年02月13日22lonelyxmas

我在我的 App.xaml 文件中定义了全局 ResourceDictionary。

<Application.Resources> 
    <ResourceDictionary> 
        <Style x:Key="yolo" TargetType="Grid" /> 
    </ResourceDictionary> 
</Application.Resources> 

我已经在随机 Page 中设置了断点并在调试器中检查了差异:

Application.Current.Resources = 1 
Resources = 0 

this.Resources 是什么?

请您参考如下方法:

Application.Current.Resources

包含在App.xaml文件中声明的资源,可以看到整个应用。

this.Resources

包含为任何控件在本地定义的资源,例如 Window、UserControl,并且仅在该控件内可用。

Window 示例:

XAML

<Window ... 
        xmlns:sys="clr-namespace:System;assembly=mscorlib" 
 
<Window.Resources> 
    <sys:String x:Key="MyString">TestString</sys:String> 
</Window.Resources> 

代码隐藏

public MainWindow() 
{ 
    InitializeComponent(); 
    string test = this.Resources["MyString"] as string; 
}