如何将TextBlock的text属性绑定到TextBox的text属性的数据 [英] How to data bind the text property of a TextBlock to the text property of a TextBox
问题描述
我有一个包含两页的WPF应用程序.在第一页上,有一个TextBox(boxSource).在第二页上,我有一个TextBlock(blockDestination).我想在XAML中将boxSource的Text属性绑定到blockDestination的Text属性.
I have a WPF application with two pages. On page one, there is a TextBox (boxSource). On page two, I have a TextBlock (blockDestination). I want to databind in XAML, the Text property of boxSource to the Text property of blockDestination.
初始化应用程序时,我将第二页的DataContext设置为第一页.我将blockDestination设置如下:
I set the DataContext of page two to page one when the application is initialized. I setup blockDestination as follows:
<TextBlock Name="blockDestination" Grid.Row="0" Grid.Column="1" Text="{Binding boxSource, Path=Text, Mode=OneWay}" />
这不会获取TextBox的值.我的猜测是因为TextBox是变量而不是属性?
This does not pickup the value of the TextBox. My guess is that it is because the TextBox is a variable instead of a property?
任何人都可以解释这个问题,并且有一个优雅的解决方案吗?
Can anyone explain the issue, and is there an elegant solution?
感谢您的帮助
推荐答案
为使该XAML正常工作,您需要将第一页"设置为第二页的数据上下文,并将boxSource变量定义为一个属性,因此,在设置器中,您可以引发PropertyChanged事件.
For that XAML to work, your "page one" will need to be set as the data context of page two, with the boxSource variable defined as a property, so that in the setter, you can raise the PropertyChanged event.
Matthias是正确的,但这是实现此目标的一种非常脆弱的方法,并且是MVVM方法从长远来看将更可靠的地方之一.
Matthias is right, though, this is a pretty brittle way to implement this, and one of the places where an MVVM approach will be more robust in the long run.
这篇关于如何将TextBlock的text属性绑定到TextBox的text属性的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!