如何在WPF中完成双向数据绑定

如何在WPF中完成双向数据绑定

本文介绍了如何在WPF中完成双向数据绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过很多有关WPF中双向绑定的信息,但对于如何完成绑定或它实际上意味着什么,我还不太清楚.

I have heard a lot about two-way bindings in WPF, but I'm not entirely clear on how to accomplish it or what it actually means.

我有一个ListView,里面有很多物品.当用户选择一个新项目时,应用程序中的TextBox会更改其文本以显示所选项目的某些属性.

I have a ListView with a bunch of items in it. When the user selects a new item, a TextBox in the application will change its text to display some property of the selected item.

但是当用户更改文本框中的文本时,我也希望ListView项目也立即更新.有没有双向绑定"神奇的WPF方式可以做到这一点?

But when the user changes the text in the text box I want the ListView item to be updated immediately as well. Is there any "two-way binding" magical WPF way of accomplishing this?

推荐答案

如果没有,则需要为要绑定的类实现INotifyPropertyChanged.

If you haven't you'll need to implement INotifyPropertyChanged for your class that you're binding to.

此外,当您说要立即更新ListBox项时,表示要在键入TextBox时对其进行更改.默认情况下,TextBox.Text属性在失去焦点时会更新其源,但是您可以通过将绑定UpdateSourceTrigger设置为PropertyChanged来更改此源:

Also, when you say you want the ListBox item to be updated immediately, you mean that you want it to change as you type in the TextBox. By default the TextBox.Text property updates its source when it loses focus, but you can change this by setting the binding UpdateSourceTrigger to PropertyChanged:

{Binding Source={...}, Path=Whatever, UpdateSourceTrigger=PropertyChanged}

这篇关于如何在WPF中完成双向数据绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:44