Accessing “current class” from WPF custom MarkupExtension

北慕城南 提交于 2019-11-29 19:30:00

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/3047448/accessing-current-class-from-wpf-custom-markupextension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!