Frage

I am trying to figure out how does wpf manage static resources at the background. For example, if i get a static resource at the code behind and set it to null or define a new object for it, changes are not reflected. But if i get static resource and change a property of it, changes are reflacted. How does wpf understands if i changed a property or set object referance and behaves this way?

Thanks for your helps.

War es hilfreich?

Lösung

Actually, this is just the standard way how the objects behave in .NET. There is some object somewhere. You get a reference to an object, and if you set your local reference to null, any other object holding the reference will not notice that -- after all, they have their own reference!

But if you change something that is "pointed to" by the reference, you change now the actual data, so everyone sees it!

Example:

class MyObject { public int i; }

MyObject ref1 = new MyObject() { i = 100 };
MyObject ref2 = ref1; // ref2 is just another reference to the object
ref1 = null;
Console.WriteLine(ref2.i); // prints 100, the object is still alive
ref1 = ref2;
ref1.i = 50;
Console.WriteLine(ref2.i); // prints 50, the object is changed

The same way it goes with static resources: you get a reference to the object, so if you null out your reference, others won't mention it: they just have another reference.

Andere Tipps

Resources that WPF binds to need to be included in a ResourceDictionary. When you get a reference to a resource in a code-behind, then you're getting a reference to a resource which has already been included in a dictionary somewhere and then making changes to it. Thus you see those changes.

If you create one from scratch via code, then unless you add it to an existing dictionary or create a new one and add it to the MergedDictionaries for the application, then WPF doesn't know it exists. See this SO question for more info on that: Programmatically add to Window.Resources in WPF

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top