Modifying a resource in C#?
I have a resource (myPoint) defined in XAML as follows:
<Path Name="myPath">
<Path.Resources>
<Point x:开发者_JS百科Key="myPoint" X="200" Y="200"/>
</Path.Resources>
</Path>
In the OnApplyTemplate override in the corresponding C# code, I use the following to get a reference to this resource.
myPointReference = (Point)myPath.FindResource("myPoint");
Now, whenever I modify the value of myPointReference, let's say,
myPointReference.X = 30;
it doesn't modify the value of the resource myPoint, it only changes the value of myPointReference. How can I make myPointReference an actual reference to my XAML defined resource myPoint so that when I modify the value of myPointReference, I am also modifying the value of myPoint?
Under the covers when you use the Resources extension in XAML you are dealing with a ResourceDictionary and you are dealing with adding a struct (aka value type) to this which will be passed by value (aka copied) into this dictionary, and then when you request it you will be returned a copy.
There is no way to pass value types by reference when dealing with a ResourceDictionary.
However, if you really need to do this after you modify your copy you can replace the old copy in the dictionary with your modified copy.
You can try this by calling:
myPath.SetResourceReference("myPoint", myPointReference)
You may want to consider not doing this in XAML or using a ResourceDictionary. You can just manage the Point in the code behind only and update it and set it to the Path as needed.
精彩评论