WPF 验证错误一直存在,直到控件失去焦点

WPF validation error remains until control loses focus

我得到了一个文本框,我在 xaml 中添加了验证规则。该规则有效并检测到错误,但只有在用户将焦点放在 window 中的某个其他元素(如另一个文本框)之后。

这是定义:

<TextBox x:Name="textBoxLongitude" Grid.Row="1" Grid.Column="1" Margin="0,0,0,10" VerticalContentAlignment="Center">
        <TextBox.Text>
            <Binding Path="CustomerLongitude">
                <Binding.ValidationRules>
                    <local:IsDoubleValidationRule MaxValue ="180"/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

我尝试通过将此添加到文本框的 xaml 来解决问题:

TextChanged="textBoxTextChanged"

以及实施:

private void textBoxTextChanged(object sender, TextChangedEventArgs e)
{
     CommandManager.InvalidateRequerySuggested();
}

没用..

即使用户不需要将焦点放在另一个控件上,我怎样才能使验证规则检测到错误以及何时修复错误?

将绑定的 UpdateSourceTrigger 设置为 PropertyChanged 以提交,并且 re-evaluate 每次更改时都设置绑定值而不是 LostFocus

Bindings that are TwoWay or OneWayToSource listen for changes in the target property and propagate them back to the source. This is known as updating the source. Usually, these updates happen whenever the target property changes. This is fine for check boxes and other simple controls, but it is usually not appropriate for text fields. Updating after every keystroke can diminish performance and it denies the user the usual opportunity to backspace and fix typing errors before committing to the new value. Therefore, the default UpdateSourceTrigger value of the Text property is LostFocus and not PropertyChanged.

操作方法:<Binding Path="CustomerLongitude" UpdateSourceTrigger="PropertyChanged">