WPF哨兵对象以及如何检查内部类型哨兵、对象、类型、WPF

由网友(一锅菠菜汤啊)分享简介:你们当中有些人已经发现,一个新的功能(?)出现WPF 4,其中数据绑定引擎可通过类的自定义控件实例 MS.Internal.NamedObject 名称为而不是数据项的code期待(这发生在一个模板控制是通过它的ItemsControl断开连接) - {DisconnectedItem} 到DataContext的...

你们当中有些人已经发现,一个新的功能(?)出现WPF 4,其中数据绑定引擎可通过类的自定义控件实例 MS.Internal.NamedObject 名称为而不是数据项的code期待(这发生在一个模板控制是通过它的ItemsControl断开连接) - {DisconnectedItem} 到DataContext的。这些被称为前哨对象。

As some of you have discovered, a new feature (?) appeared WPF 4, where the data binding engine may pass your custom control instances of the class MS.Internal.NamedObject with the name "{DisconnectedItem}" into the DataContext - instead of the data item your code is expecting (this happens when a templated control is disconnected by its ItemsControl). These are called sentinel objects.

在现有的code,这可能导致虚假的例外情况,其中code是ppared它未$ P $。这些可以吞噬数据绑定子系统,也可以肆虐。保持你的调试控制台上的眼睛。

In existing code, this can lead to spurious exceptions where the code is unprepared for it. These can be swallowed up by the data binding subsystem, or they can wreak havoc. Keep an eye on your debug console.

不管怎样,我得知这个情况在this MSDN论坛。而且有一个职位山姆弯曲而explains这一切的。现在去阅读它,你要知道这个的。其实质是,这些事件不应该解雇(这是错误),因此:

Anyway, I learned about this on this MSDN forum. And there's a post by Sam Bent which explains it all. Go read it now, you'll want to know this. The essence is that these events should never have fired (that's the bug), so:

忽略DataContextChanged仅事件,如果   在DataContext是一个定点的对象。

Ignore the DataContextChanged event if the DataContext is a sentinel object.

所以,所以我想检查我的DataContext。但如何?试想一下:

So, so I want to check my DataContext. But how? Consider:

public bool IsSentinelObject(object dataContext)
{
    return (dataContext is MS.Internal.NamedObject);
}

猜猜会发生什么?它不会编译,因为MS.Internal.NamedObject是内部的,而不是接近我。当然,我可以破解它是这样的:

Guess what happens? It doesn't compile because MS.Internal.NamedObject is internal, and not accessible to me. Of course, I can hack it like this:

public bool IsSentinelObject(object dataContext)
{
    return dataContext.GetType().FullName == "MS.Internal.NamedObject"
           || dataContext.ToString() == "{DisconnectedObject}";
}

(或东西,它的工作原理)。我也跟着山姆的建议,缓存供以后参考平等检查的对象(这是一个单例)。

(or something, which works). I have also followed Sam's suggestion to cache the object for later reference equality checks (it's a singleton).

当然,这意味着我不会有问题,不是真的。不过我很好奇,这个帖子一定会受益一些用户,所以它是值得一问呢:

Of course, this means I don't have a problem, not really. But I'm curious, and this posting will be sure to benefit some users, so it's worth asking anyway:

有没有一种方法,我可以准确地核对内部NamedObject类型的类型,而不是诉诸字符串比较?

Is there a way I can exactly check the type against the internal NamedObject type, without resorting to string comparisons?

推荐答案

这一个?

var disconnectedItem = typeof(System.Windows.Data.BindingExpressionBase)
    .GetField("DisconnectedItem", BindingFlags.Static | BindingFlags.NonPublic)
    .GetValue(null);
阅读全文

相关推荐

最新文章