c# - 导致绑定(bind)不更新的验证错误

标签 c# .net wpf xaml

我在涉足 WPF 并注意到一个我以前从未见过的特性。在下面的示例中,我有两个文本框绑定(bind)到代码隐藏中的同一个 DP。

代码隐藏:

public partial class MainWindow : Window
{
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(Window), new FrameworkPropertyMetadata("Hello"));

    public MainWindow()
    {
        InitializeComponent();
    }


}

XAML:

    <TextBox>
        <TextBox.Text>
            <Binding RelativeSource = "{RelativeSource Mode=FindAncestor, AncestorType=Window}" Path="Text" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
                <Binding.ValidationRules>
                    <utils:RestrictInputValidator Restriction="IntegersOnly" ValidatesOnTargetUpdated="True"/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
    <TextBox Name="TextBox" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Mode=TwoWay, Path=Text, UpdateSourceTrigger=PropertyChanged}"/>

我注意到,当我在包含 IntegerOnly 验证但未通过验证的 TextBox 中键入内容时(在本例中为非整数的任何内容),基础 Text 变量不会更新。 这是默认行为吗?为什么要这样做?是否可以覆盖?

Error example

最佳答案

将 ValidationRule 的 ValidationStep 设置为 CommitedValue,这将在值提交到源 (msdn) 后运行验证。

<utils:RestrictInputValidator Restriction="IntegersOnly" ValidationStep="CommitedValue" ValidatesOnTargetUpdated="True"/>

编辑: 将 validationstep 设置为 CommitedValue 或 UpdatedValue 时,BindingExpression 将发送到 Validate 方法,而不是实际值。我不知道是否有另一种方法来获取 BindingExpression 的值,但我制作了一个扩展方法来获取它:

public static class BindingExtensions
{
    public static T Evaluate<T>(this BindingExpression bindingExpr)
    {
        Type resolvedType = bindingExpr.ResolvedSource.GetType();
        PropertyInfo prop = resolvedType.GetProperty(
            bindingExpr.ResolvedSourcePropertyName);
        return (T)prop.GetValue(bindingExpr.ResolvedSource);
    }
}

关于c# - 导致绑定(bind)不更新的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602579/

相关文章:

c# - Visual Studio 扩展包是否支持异步操作

c# - Azure函数不运行异步方法

c# - Winform 应用程序第一个 Web 请求很慢

.net - RazorEngine - 如果仅在 View 中使用,则不会加载引用的程序集

c# - 如何为 FileHelpers 元素类的字段定义默认值

c# - 我如何从后面的 C# 代码动态创建 html 元素?

c# - 如何禁止在 .NET 中将按键打印到控制台?

javascript - AngularJS 指令上有类似 DependencyProperty 的功能吗?

c# - 使用基础和MVVM通信在构造函数处进行C#继承

c# - WPF: program.exe 不退出 "the process cannot access the file.. used by another process"