如何在ControlBindingCollection中找到特定的绑定?

时间:2019-06-22 23:19:48

标签: c# data-binding

我正在尝试向代码中添加AlreadyBound方法,以便避免错误

HResult=0x80070057 This causes two bindings in the collection to bind to the same property.

调用
System.Windows.Forms.ControlBindingsCollection.CheckDuplicates(Binding binding)

我的代码是

        public static void BindText(TextBox box, object dataSource, string dataMember)
    {

        if (AlreadyBound(box,"Text")) return;

        box.DataBindings.Add("Text", dataSource, dataMember, true, DataSourceUpdateMode.OnPropertyChanged);
        if (!(box is SnapTextBox snapbox)) return;
        switch (snapbox.SnapType)
        {
            case SnapBoxType.Money:
                snapbox.DataBindings[0].FormatString = "N2";
                break;
            case SnapBoxType.Real:
                snapbox.DataBindings[0].FormatString = $"N{snapbox.SnapRealDecimals}";
                break;
            case SnapBoxType.Text:
                break;
            case SnapBoxType.Integer:
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }

    private static bool AlreadyBound(TextBox box, string propertyName)
    {
        foreach (var binding in box.DataBindings)
        {
            // what do I put here?  something like
            //if (binding.ToString() == propertyName) return true; 
        }

        return false;
    }

其中SnapTextBox是用户定义的控件。

如何使AlreadyBound工作?

1 个答案:

答案 0 :(得分:0)

我很难弄清楚应将哪种类型的绑定声明为。 最后,我尝试查看box.DataBindings [0]

的类型
    private static bool AlreadyBound(TextBox box, string propertyName)
    {
        foreach (Binding binding in box.DataBindings)
        {
            if (binding.PropertyName == propertyName) return true; 
        }
        return false;
    }