.NET Databinding忽略属性更改

时间:2008-11-26 10:39:19

标签: c# data-binding

我在C#中编写了一个派生自System.Windows.Forms.Control的控件。我已经使用BindingSource添加了一个属性Selected,我想将其数据绑定到业务实体。

我已经通过添加SelectedChanged事件来实现PropertyNameChanged模式,当我更改Selected属性时,我会触发该事件。

这是我的代码:

public partial class RateControl : Control
{
    [Category("Property Changed")]
    public event EventHandler SelectedChanged;

    public int Selected
    {
      get
      { return m_selected; }
      set
      {
        if (m_selected != value)
        {
          m_selected = value;
          OnSelectedChanged();
          Invalidate();
        }
      }
    }

    protected virtual void OnSelectedChanged()
    {
      if (this.SelectedChanged != null)
        this.SelectedChanged(this, new EventArgs());
    }
}

当我绑定到Selected属性时,我看到事件正在被子类化。当属性发生变化时,也会触发该事件。

但是,业务实体未更新。我甚至没有看到被访问的Selected属性的getter。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

您是否已将绑定的更新模式设置为DataSourceUpdateMode.OnPropertyChanged?可以通过binding.DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;,也可以使用其中一个DataBindings.Add(...)重载。

以下内容适用于将值推送到业务对象...

using System;
using System.Diagnostics;
using System.Windows.Forms;

class MyForm : Form
{
    public MyForm()
    {
        MyBusinessObject obj = new MyBusinessObject();
        Button btn = new Button();
        btn.Click += delegate { Foo++; };
        DataBindings.Add("Foo", obj, "Bar", false, DataSourceUpdateMode.OnPropertyChanged);
        DataBindings.Add("Text", obj, "Bar");
        Controls.Add(btn);
    }

    private int foo;
    public event EventHandler FooChanged;
    public int Foo
    {
        get { return foo; }
        set
        {
            if (foo != value)
            {
                foo = value;
                Debug.WriteLine("Foo changed to " + foo);
                if (FooChanged != null) FooChanged(this, EventArgs.Empty);
            }
        }
    }
}

class MyBusinessObject
{
    private int bar;
    public event EventHandler BarChanged;
    public int Bar
    {
        get { return bar; }
        set
        {
            if (bar != value)
            {
                bar = value;
                Debug.WriteLine("Bar changed to " + bar);
                if (BarChanged != null) BarChanged(this, EventArgs.Empty);
            }
        }
    }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.Run(new MyForm());
    }
}