【问题标题】:Execute WPF Element validation in C#?在 C# 中执行 WPF 元素验证?
【发布时间】:2009-10-21 17:15:40
【问题描述】:

当用户点击按钮时如何强制验证?

人们会认为这应该很容易,因为如果元素值有效,您总是需要做一些事情。

private void buttonOk_Click(object sender, RoutedEventArgs e)
{
    // How can I force the validation here? So that empty values are not allowed (validator doesn't allow those)

    if (Validation.GetHasError(textBoxURI) ||
        Validation.GetHasError(textBoxName)) // These return valid values if user has not changed values in fields.
        return;

    DialogResult = true;
    this.Close();
}

你可以猜到,根据我的验证器,空值是无效的(如果我在文本框中输入一些内容)然后清空它并模糊焦点它将显示无效值。

附带说明:UpdateSourceTrigger 不会影响初始值未验证的相关问题。

【问题讨论】:

    标签: c# wpf .net-3.5


    【解决方案1】:

    您需要在 BindingExpression 上调用 UpdateSource。这是一个带有文本框的示例,我们在其中强制进行验证:

    BindingExpression exp = textBox.GetBindingExpression(TextBox.TextProperty);
    exp.UpdateSource();
    

    【讨论】:

      【解决方案2】:

      您是否尝试过使用 MultiTriggerMultiDataTrigger

      使用它,您可以定义您当前的规则......以及您可能想出的任何其他验证规则。

      Check this out:

      【讨论】:

      • 我确实读过它,是的,有人做了一些条件来停止使用这些按钮启用“确定”按钮......
      • 如果你知道如何使用 MultiTrigger 将 DialogResult 设置为 true,那我就很难做到。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2015-01-29
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      相关资源
      最近更新 更多