绑定数据到自定义控件

7

我有一个自定义控件(Windows Form),它是一个查找文本框。控件上的一个属性是当前选择,它是一个包含“标识符”,“代码”和“描述”的自定义对象。该属性使用BindingSource进行数据绑定。

显示信息非常好用。另一方面,无论我将更新设置为OnValidate还是OnValueChange,它都不会更新BindingSource。我是否遗漏了什么以使其自动更新?

private System.Windows.Forms.BindingSource buildPlanComponentDataBindingSource;

    public void LoadBuildPlan(string itemNumber)
    {
        var buildPlanComponents = BuildPlan.LoadBuildPlanComponents(itemNumber, AutomaticPrice);
        buildPlanComponentDataBindingSource.DataSource = buildPlanComponents;
        AssemblyNumber = itemNumber;
    }




[Bindable(true)]
[DefaultValue(null)]
public ILookupSelection CurrentSelection
{
    get
    {
        if (currentSelection == null)
            currentSelection = new LookupSelection {Code = txtLookup.Text};

        return currentSelection;
    }

    set
    {
        if (value == null) return;

        currentSelection = value;

        SetText(currentSelection, DisplayText);
        SetDescription(currentSelection, DisplayDescription);
    }
}

你能展示一下你创建数据绑定的代码吗? - overslacked
谢谢,你的问题非常有帮助。由于某种原因,MSDN教程在教程中省略了[Bindable(true)]属性。这是一个重要的细节! - Jason L.
3个回答

2
实现INotifyPropertyChanged似乎是解决方案!
    #region IPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (null != PropertyChanged)
        {
            PropertyChanged(this, e);
        }
    }

    #endregion

IPropertyChanged 应该改为 INotifyPropertyChanged。在定义继承关系时,我复制了代码并被这个细节所欺骗。其他方面都很棒,点赞+1。 - Marcel

0
也许您需要引起数据绑定为每个控件编写其值,以便通过此方式设置值?
假设一个名为txtMySetValue的文本框有一个数据绑定:

txtMySetValue.DataBindings[0].WriteValue();


0
显示信息很好。然而,无论我将更新设置为OnValidate还是OnValueChange,它都不会更新BindingSource。
看了你的代码后,我对此并不确定。在你的设置中,你测试了null并放弃;如果数据实际上包含null(这就是你所描述的),你的控件将不同步。我想知道是否这个检查掩盖了潜在的问题。

唯一真正为NULL的时候是在控件初始创建时。否则,只有在包含值的选择被创建时才会设置。 - ejmack
如果是这种情况,我建议您使用与 value == null 不同的标志进行测试。属性的数据绑定是一个来回的过程...无论如何,我会清理一下这个部分,但我也不确定最终是否能解决您的问题。 - overslacked

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接