【问题标题】:validation not fired unless you type除非您键入,否则不会触发验证
【发布时间】:2015-05-04 07:05:42
【问题描述】:

我在 WPF 窗口中有三个文本框,UpdateSourceTrigger="LostFocus"。 我还有一个验证类 (:ValidationRule),它根据我的条件返回 false 或 true,并保持简单:条件是检查字符串是否为空。

<TextBox x:Name="TestBox">
    <TextBox.Text>
        <Binding ElementName="This" Path="test" 
         UpdateSourceTrigger="LostFocus">
            <Binding.ValidationRules>
                <local:IPv4ValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>
<TextBlock Margin="2" Foreground="Red" FontWeight="Bold" 
       Text="{Binding ElementName=TestBox, 
                      Path=(Validation.Errors),
                      Converter={StaticResource eToMConverter}}" />

问题是: 如果您运行应用程序并浏览文本框,则不会在失去焦点时显示错误。我在代码中放了一个按钮来触发验证,没有显示错误。

只有在您输入文本框然后清除它时,验证才会起作用。

我该如何解决这个问题?因为在这种情况下,我无法确认是否有人将文本框留空,除非他输入然后删除。

【问题讨论】:

    标签: wpf validation


    【解决方案1】:

    阅读MSDN,你会发现:

    验证通常发生在将目标的值转移到 绑定源属性。

    因此,除非您更新源,否则不会在不输入密钥的情况下评估您的验证规则。 你可以在后面的代码中做到这一点。假设MainWindow 是您的窗口,您需要添加一个Loaded 事件处理程序:

    public MainWindow()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }
    
    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        BindingExpression bindingExpression = TestBox.GetBindingExpression(TextBox.TextProperty);
        bindingExpression.UpdateSource();
    }
    

    如您所见,处理程序的代码会更新源代码,因此会评估 ValidationRule

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 2020-12-07
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 2010-09-27
      相关资源
      最近更新 更多