【问题标题】:Databinding a Custom Control数据绑定自定义控件
【发布时间】:2010-10-11 01:36:15
【问题描述】:

我有一个自定义控件(Windows 窗体),它是一个查找文本框。控件上的一个属性是当前选择,它是一个包含“标识符”、“代码”和“描述”的自定义对象。此属性是使用 BindingSource 的 Databound。

显示信息效果很好。另一方面,无论我将 Update 设置为 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);
    }
}

【问题讨论】:

  • 您能告诉我们您创建数据绑定的代码吗?
  • 谢谢,您的问题很有帮助。出于某种原因,MSDN 教程在其教程中省略了 [Bindable(true)] 属性。这是一个重要的细节!

标签: c# winforms controls


【解决方案1】:

实施 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
【解决方案2】:

显示信息作品 伟大的。另一方面不管 我是否将更新设置为 OnValidate 或 OnValueChange 它永远不会更新 绑定源。

查看您的代码,我实际上不确定这一点。在您的集合中,您测试 null 和放弃;如果数据实际上包含 null (这是您所描述的),您的控制将不同步。我想知道该检查是否掩盖了根本问题。

【讨论】:

  • 唯一真正为 NULL 的时间是控件最初创建的时候。否则,只有在进行包含值的选择时才会设置。
  • 如果是这种情况,那么我建议您使用不同的标志进行测试,而不是 value == null。数据绑定到属性是一个来回的过程......无论如何,我会清理这一点,但我也不肯定它最终会帮助你解决问题。
【解决方案3】:

也许您需要让 DataBinding 为您以这种方式设置其值的每个控件写入其值?

假设一个名为 txtMySetValue 的文本框有一个数据绑定:

txtMySetValue.DataBindings[0].WriteValue();

【讨论】:

    猜你喜欢
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2011-04-27
    相关资源
    最近更新 更多