简体   繁体   English

WPF,UpdateSourceTrigger = Explicit的数据绑定问题

[英]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. 我正在使用UpdateSourceTrigger = Explicit对文本块进行数据绑定,因为我希望仅在单击按钮时才进行更新。 The task is to fill a text box and after entering a button, a textblock to be updated. 任务是填充文本框,输入按钮后,将更新一个文本块。

Here is my XAML: 这是我的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. 在绑定中,无法从我的XAML识别txtMaxItems,它表示未声明txtMaxItems,而且我不知道为什么。 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. 正如dkozl的评论所提到的,UpdateSource将值从目标(您的视图)发送到源(您的视图模型),因此您的代码有效地将TextBlock的值发送到您的视图模型。

Also, you have two different binding paths – MyTile.MaxItems in the TextBox and MaxItems in the TextBlock . 此外,你有两个不同的结合路径- MyTile.MaxItemsTextBoxMaxItemsTextBlock This makes sense if they are binding to different data contexts, where one exposes the other as a property called MyTile . 如果它们绑定到不同的数据上下文,则这是有道理的,其中一个上下文将另一个暴露为称为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. 在从TextBox控件而不是TextBlock控件检索的绑定表达式上调用UpdateSource。 That will take the value that is in the TextBox and send it to its data context. 这将采用TextBox的值并将其发送到其数据上下文。 If the TextBlock is bound to the same property, then it will update once the source changes. 如果TextBlock绑定到相同的属性,则源更改后它将更新。
  2. Remove Mode=TwoWay from the binding in the TextBlock . TextBlock的绑定中删除Mode=TwoWay 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. 除非您以编程方式直接在该控件上设置文本,否则它将永远没有理由将其值发送到其数据上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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