问题描述
我正在尝试编写一个自定义 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).
这可能吗?
推荐答案
在 .NET 4.0 中,他们添加了 IRootObjectProvider 能力,但不幸的是,在以前的版本中是不可能的.如果您使用的是 .NET 4.0,则可以执行以下操作:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!