简体   繁体   中英

WPF, data binding issue with UpdateSourceTrigger=Explicit

I am using data binding for textblock with UpdateSourceTrigger=Explicit, because I want the update to happen only when a button is clicked. The task is to fill a text box and after entering a button, a textblock to be updated.

Here is my XAML:

<TextBox Grid.Column="1" Grid.Row="3" HorizontalAlignment="Left"
                 Margin="10,5,0,5" Width="75"
                 Text="{Binding MyTile.MaxItems, UpdateSourceTrigger=Explicit}" />

and

<TextBlock x:Name="txtMaxItems" Text="{Binding MaxItems, Mode=TwoWay}" VerticalAlignment="Center" HorizontalAlignment="Center" />

Here I do my binding:

Dim binding As BindingExpression = txtMaxItem.GetBindingExpression(TextBlock.TextProperty)
    binding.UpdateSource()

In the binding, the txtMaxItems is not recognized from my XAML, it says that txtMaxItems is not declared and I cannot realize why. Please advise.

It looks like you have some things mixed up with your bindings. As dkozl's comment mentions, UpdateSource send the value from the target (your views) to the source (your view model), so your code is effectively sending the value that is in the TextBlock to your view model.

Also, you have two different binding paths – MyTile.MaxItems in the TextBox and MaxItems in the TextBlock . This makes sense if they are binding to different data contexts, where one exposes the other as a property called MyTile . If that is not the case, you might have an issue there.

I would start by making these changes:

  1. Call UpdateSource on a binding expression retrieved from the TextBox control, rather than the TextBlock control. That will take the value that is in the TextBox and send it to its data context. If the TextBlock is bound to the same property, then it will update once the source changes.
  2. Remove Mode=TwoWay from the binding in the TextBlock . Unless you are programmatically setting the text directly on that control, then it is never going to have a reason to send its value to its data context.

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