访问“当前类别".从WPF自定义MarkupExtension [英] Accessing "current class" from WPF custom MarkupExtension
问题描述
我正在尝试编写自定义的 MarkupExtension
,以便通过给我一种更好的在XAML中指定绑定的方式来简化我的生活.但是我想知道是否有什么方法可以访问表示使用 MarkupExtension
的文件的对象.
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.
换句话说,假设我有一个 UserControl
,它定义了程序数据模型的特定格式.该控件具有许多可视化内容,例如网格,边框和总体布局.如果我在此 UserControl
中某个元素的特定属性上使用 MarkupExtension
,我想访问 UserControl
的实例,而又不知道键入它(我打算使用反射).
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).
这有可能吗?
推荐答案
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
}
这篇关于访问“当前类别".从WPF自定义MarkupExtension的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!