简体   繁体   English

C# 覆盖 OnValidating 以支持 null 值但破坏数据绑定

[英]C# Override OnValidating to support null value but breaks Data Binding

I have a CustomTextBox which inherits from TextBox and overwrites the OnValidating method to allow empty strings.我有一个继承自 TextBox 并覆盖 OnValidating 方法以允许空字符串的 CustomTextBox。 CustomTextBox is bound to Property Price in Domain. CustomTextBox 绑定到域中的 Property Price。

public class CustomTextBox
{
    protected override void OnValidating(...)
    {  
       if(Text=="") 
       {
           Text = null;
           return;
       }
       base.OnValidating(e);
    }
}
public class Domain
{
    public System.Nullable<decimale> Price
    { ... }
}

All works well except that this prevents users froming setting Price to null.除了这会阻止用户将价格设置为 null 之外,一切都运行良好。 Text=null; did not propogate to the domain object.没有传播到域 object。 Is there a way to reset Price back to null when user clears out the TextBox?当用户清除文本框时,有没有办法将价格重置回 null?

If you are using Binding to propagate values to the domain object, then you should put this logic in the Parse event instead.如果您使用绑定将值传播到域 object,那么您应该将此逻辑放在Parse 事件中

// Add binding
var b = new Binding("Text", myDataSource, "BoundProperty");
b.Parse += OnNullableTextBindingParsed;
myTextBox.DataBindings.Add(b);


// Sample parse handler
private void OnNullableTextBindingParsed(object sender, ConverterEventArgs e)
{
    if (e.Value == String.Empty) e.Value = null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM