在 XAML 中指定 DataContext 并将其用于下一个属性中的绑定
考虑以下代码:
<MyControl DataContext="{Binding DataObject}" Text="{Binding DisplayText}"/>
据我所知,XAML 属性是按声明顺序分配的。然而,就 XML 而言,依赖它是一个糟糕的设计。我想我可以将其重写为如下所示:
<Grid DataContext="{Binding DataObject}">
<MyControl Text="{Binding DisplayText}"/>
</Grid>
但是,仅出于语义而放置网格对我来说似乎是错误的。
你怎么认为?
谢谢!
维塔利
Consider the following code:
<MyControl DataContext="{Binding DataObject}" Text="{Binding DisplayText}"/>
As far as I know, XAML attributes are assigned by the order they are declared. However, XML-wise, depending on it is a bad design. I guess I could rewrite it to look like so:
<Grid DataContext="{Binding DataObject}">
<MyControl Text="{Binding DisplayText}"/>
</Grid>
However, putting a Grid just for semantics seems wrong to me.
What do you think?
Thanks!
Vitaly
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对你的问题有点困惑。这些属性的设置顺序并没有真正的区别。当文本属性设置为绑定时,就像您所做的那样,它所做的就是创建一个绑定到 Text 属性并具有“DisplayText”路径的绑定。只要在评估绑定时(稍后发生)设置 DataContext 就可以了。
I'm a little confused by your question. The order in which those attributes are set doesn't really make a difference. When the text attribute is set to the binding as you've done it, all it does is create a Binding that is tied to the Text property and has a Path of "DisplayText". As long as the DataContext is set at the time that the binding is evaluated (which occurs sometime later) then you're fine.
无论如何,不建议使用网格,因为它会影响性能,如果您没有选择(没有父级可放置上下文),请使用边框
Grid is not recommended anyway cause it's effect performance, if you have no chiose(no parent to put context in) use a border