请考虑以下示例。请注意,在现实世界中,绑定源很可能是一个数据对象。为了简单起见,我使用 a TextBlock。
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel Margin="20">
<Label>Enter a Name:</Label>
<TextBox x:Name="txt_Name" Text="{Binding ElementName=display_name, Path=Text, UpdateSourceTrigger=LostFocus}" />
<Label>The name you entered:</Label>
<TextBlock x:Name="display_name" />
<Button x:Name="btn_Save" Click="SaveClick">_Save</Button>
</StackPanel>
</Window>
Class Window1
Private Sub SaveClick(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
MessageBox.Show("Saving your name as: " & display_name.Text)
End Sub
End Class
在上面的示例中,如果我在 中输入名称"Joe"并TextBox单击“保存”按钮,TextBlock则会更新LostFocus并正确“保存”数据。一切都很好。
但是,如果我随后输入"Bob"并TextBox使用我的访问密钥 (Alt-S) 进行保存,TextBlock则不会更新,因为不会触发LostFocus上的事件。TextBox结果,我的绑定源没有更新,并且"Joe"保存了错误的值(即 )。
在大多数 WPFTextBox数据输入字段中,您需要在LostFocus(not PropertyChanged) 上进行验证;但是,如果在LostFocus使用访问密钥时事件没有触发(因此绑定没有更新),我们如何验证条目?在 WinForms 中我们有ValidatingandValidated事件,但在 WPF 中没有它们。