通常您不希望UpdateSourceTrigger
处于绑定状态,因为这会PropertyChanged
在TextBox.Text
每次按下键时触发验证和更改通知。
如果您这样做只是为了如果用户点击 Enter 它将在处理保存命令之前保存该值,那么我建议挂钩PreviewKeyDown
事件并在按下的键为 Enter 时手动更新源(通常我将其设为附加属性)
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
var obj = sender as UIElement;
BindingExpression textBinding = BindingOperations.GetBindingExpression(
obj, TextBox.TextProperty);
if (textBinding != null)
textBinding.UpdateSource();
}
}
但是话虽如此,如果您仍想使用UpdateSourceTrigger=PropertyChanged
,则在显示值时考虑使用格式,但在用户编辑时将其删除。
<TextBox>
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Text" Value="{Binding Path=MyDoubleValue, StringFormat=N2}" />
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Text" Value="{Binding Path=MyDoubleValue, UpdateSourceTrigger=PropertyChanged}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>