是“{绑定路径=.}"吗?和“{绑定}"真的平等 [英] Are "{Binding Path=.}" and "{Binding}" really equal
问题描述
在我的 WPF 项目中,我有一个 ListBox,用于显示 List
集合中的项目.我想让这些项目的文本可编辑,所以我将它们中的每一个都包裹在一个带有 TextBox 的 ItemTemplate 中(可能不是最好的方法,但我是 WPF 的新手).我在简单地将 TextBoxes 的 Text 属性绑定到每个项目的值时遇到了麻烦.我终于偶然发现了一个使用单个点或句点作为其 Path 属性的示例 ({Binding Path=.}
):
In my WPF project, I have a ListBox that displays items from a List<string>
collection. I wanted to make the text of these items editable, so I wrapped each of them in an ItemTemplate with a TextBox (might not be the best way, but I'm new to WPF). I was having trouble simply binding the TextBoxes' Text property to the value of each item. I finally stumbled upon an example using a single dot or period for its Path property ({Binding Path=.}
):
<ListBox ItemsSource="{Binding ElementName=recipesListbox,Path=SelectedItem.Steps}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=.}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
但是我不明白为什么简单地使用 {Binding}
不起作用.
However I don't understand why simply using {Binding}
didn't work.
它引发了双向绑定需要 Path 或 XPath"异常,如 根据微软:
It raised a "Two-way binding requires Path or XPath" exception, as according to Microsoft:
[...] 句点 (.) 路径可用于绑定到当前源.例如,Text="{Binding}" 等价于 Text="{Binding Path=.}"
有人可以解释这种模棱两可的行为吗?
Could someone shed light on this ambiguous behavior?
而且,似乎 {Binding Path=.}
不一定给出双向绑定,因为修改文本和移动焦点不会更新基础源(同一源还具有在 DataGrid 控件上显示和成功修改的属性).我肯定在这里遗漏了一些东西.
Moreover, it seems {Binding Path=.}
does not necessarily give two-way binding, as modifying the text and moving the focus does not update the underlying source (the same source has also properties displayed and successfully modified on a DataGrid control). I'm definitely missing something here.
推荐答案
异常的点大概是你不能双向绑定绑定源本身,所以它试图阻止你创建一个不绑定按照您希望的方式行事.通过使用 {Binding Path=.}
你只是欺骗了错误处理.
The point of the exception presumably is that you cannot two-way bind a binding-source itself, so it tries to prevent you from creating a binding which does not behave the way you would want it to. By using {Binding Path=.}
you just trick the error handling.
(也不是没有听说过该文档是错误的或不准确的,尽管我确实非常喜欢 MSDN 文档,因为它通常包含人们感兴趣的关键点)
这篇关于是“{绑定路径=.}"吗?和“{绑定}"真的平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!