.NET Databinding ignores property changes

I wrote a control in C # that comes from System.Windows.Forms.Control. I added a Selected property to which I want to bind data to a business object using a BindingSource.

I've implemented the PropertyNameChanged pattern by adding a SelectedChanged event that I fire when the Selected property changes.

This is my code:

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());
    }
}

      

When I bind to the Selected property, I can see that the event is pegged. The event is also triggered when the property changes.

However, the business object is not updated. I don't even see access to the getter of the Selected property.

What am I missing?

+1


source to share


1 answer


Do you have the binding mode set to DataSourceUpdateMode.OnPropertyChanged? Either through binding.DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;

or using one of the overloads DataBindings.Add(...)

.

The following works for me to pass values ​​to a business object ...



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());
    }
}

      

+1


source







All Articles