简体   繁体   中英

What is the difference between Application.Current.Resources and Resources

I have global ResourceDictionary defined in my App.xaml file.

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

I've had set breakpoint in random Page and checked difference in debugger:

Application.Current.Resources = 1
Resources = 0

What's the this.Resources ?

What's the this.Resources ?

It's the resource dictionary of the control whose code-behind code we are writing in.

On the other hand Application.Current.Resources is the resource dictionary of the application object itself.

If you are writing code inside App.xaml.cs , then Resources and Application.Current.Resources will refer to the same object.

Application.Current.Resources

Contains the resources that are declared in the App.xaml file, which can be seen the entire application.

this.Resources

Contains the resources that are defined locally for any control, such as Window , UserControl and are only available within this control.

Example with Window :

XAML

<Window ...
        xmlns:sys="clr-namespace:System;assembly=mscorlib"

<Window.Resources>
    <sys:String x:Key="MyString">TestString</sys:String>
</Window.Resources>

Code-behind

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM