Why can't I use {x:Bind {RelativeSource Self}} in a data template?

前端 未结 2 1758
星月不相逢
星月不相逢 2021-01-03 02:25

If I use {x:Bind {RelativeSource Self}} in a data template, I get the following error while compiling:

Object reference not set to an ins

2条回答
  •  既然无缘
    2021-01-03 02:58

    Let me more specifically answer this. There is only one possible data context to x:bind and that is the underlying class. On a page, it is the page (or the code-behind). In a data template, it is the backing class specified in the targettype property of the data template. As an aside, in a control template, x:bind is not supported at all - though it's only a matter of time.

    All that is to say that the data context of x:bind is fixed, and depending on where it is being used, I can tell you the data context without looking at your XAML. Why so rigid? In part to make the code generation around it simpler. Also, to make the implementation simpler, too. In either case, this is a fixed rule, and RelativeSource, ElementName, and Source and not supported in x:bind.

    This does not mean you cannot reference the relativesource self, you just have to do it with a specified x:name. You would do something like this .

    Why does that particular sample fail? Unlike {binding}, {x:bind} requires matching types, which means setting Text's string can be down-cast and set to Tag's object, but Tag's object cannot be up-cast and set to Text's string value. The take-away for you is using x:bind means your types must match.

    I hope this helps get you further along.

    Best of luck.

提交回复
热议问题