Accessing "current class" from WPF custom MarkupExtension
Asked Answered
F

1

10

I'm attempting to write a custom MarkupExtension to make my life easier by giving me a better way to specify bindings in XAML. However I would like to know if there is any way I can access the object that represents the file the MarkupExtension is used in.

In other words, suppose I have a UserControl that defines a particular rendition of a data model of my program. This control has lots of visual stuff like grids, borders and general layout. If I use my MarkupExtension on a particular property of some element in this UserControl, I want to access the instance of the UserControl, without knowing what type it is (I plan on using reflection).

Is this at all possible?

Finality answered 15/6, 2010 at 17:21 Comment(0)
N
16

In .NET 4.0, they added the IRootObjectProvider ability, but unfortunately, it isn't possible in previous versions. If you are in .NET 4.0, you can do the following:

public override object ProvideValue(IServiceProvider serviceProvider)
{
    var rootObjectProvider = serviceProvider.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
    var root = rootObjectProvider.RootObject;
    // do whatever you need to do here
}
Nedry answered 15/6, 2010 at 17:46 Comment(4)
I am using .NET 4! Lemme try it out. :)Finality
No other way for us, stuck in 3.5?! :((((((((((Aprilaprile
In .NET 3.5, you only have access to IXamlTypeResolver and IProvideValueTarget. Unfortunately, they won't get you the object at the root of the xaml file you are working in. IProvideValueTarget will allow you to get the object the extension is called on. I suppose you could walk up its visual tree to get to the root object, if you assume that the root is a UserControl or Window. This obviously isn't as robust as the .NET 4 solution, but it might work in your scenario.Nedry
Note that for custom controls (not user controls) the root object is the ResourceDictionary :-(Ineffable

© 2022 - 2024 — McMap. All rights reserved.