简体   繁体   中英

How to bind two elements to the same property in WPF - C#

I'm using C# in a WPF application with MVVM (with Caliburn Micro framework). I'm trying to bind 2 elements (one TextBlock and one TextBox) to the same property, that resides in my model view. My property is called FirstName . I have two options to do the binding: Binding Path=FirstName or x:Name=FirstName . When I edit the textbox, I see the changes in the textblock only if I bind in a certain way (see code). Any idea of why the other way does not work? (when I type in the textbox I don't see my textblock updates)

I've tried different mode options (two ways, one way, etc). The NotifyOfPropertyChange seems to be working.

<!-- This works -->
<TextBlock Text="{Binding Path=FirstName}"/>
<TextBox x:Name="FirstName"/>

<!-- This does not work -->
<TextBlock x:Name="FirstName"/>
<TextBox Text="{Binding Path=FirstName, Mode=TwoWay}"/>

With your second example, you need to specify UpdateSourceTrigger=PropertyChanged :

<TextBlock x:Name="FirstName"/>
<TextBox Text="{Binding Path=FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

Otherwise, the source is only updated when the TextBox loses focus.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM