DataBinding in UserControl not working at design time?

I have a little question regarding data binding and user controls.

I am creating (using C # 2010) a user control that is basically a wrapper for ComboBox and has a custom property that, when changed, sets the value of ComboBox. Conversely, if the selected item in the ComboBox changes, the value of the property changes.

Now I could do this by capturing the “selected value changed” event in the ComboBox and setting the property, and I could set the selected ComboBox value in the property adjuster, but I assumed that I could also be able to do this using a DataBinding.

And it almost works, but not quite.

It works at runtime, but not at development time, and I was wondering if this is easy to solve.

For example, if during development I select an instance of my user control and select my control user property in the properties window and change it, the ComboBox does not reflect the change.

Any pointers to something that I missed would be greatly appreciated. Obviously, I could set the selected value to ComboBox, but it would be nice if DataBinding did this for me.

Thanks
Ross

(Here is my user control. Drop it on the form and use the IDE to change the Position property)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace WindowsFormsApplication13
{
  public partial class UserControl1 : UserControl, INotifyPropertyChanged
  {
     public event PropertyChangedEventHandler PropertyChanged;

     public enum enumPosition : byte
     {
        Unknown, First, Second, Third
     }

     public UserControl1()
     {
        InitializeComponent();

        var bindingList = new BindingList<KeyValuePair<enumPosition, String>>();

        foreach (enumPosition value in Enum.GetValues(typeof(enumPosition)))
        {
           bindingList.Add(new KeyValuePair<enumPosition, String>(value, value.ToString()));
        }

        this.comboBox1.DisplayMember = "Value";
        this.comboBox1.ValueMember = "Key";
        this.comboBox1.DataSource = bindingList;

        this.comboBox1.DataBindings.Add("SelectedValue", this, "Position", false, DataSourceUpdateMode.OnPropertyChanged);
     }

     private enumPosition _position = enumPosition.Unknown;

     [DefaultValue(typeof(enumPosition), "Unknown")]
     public enumPosition Position
     {
        get { return _position; }
        set
        {
           if (value != _position)
           {
              _position = value;
              this.OnPropertyChanged(new PropertyChangedEventArgs("Position"));
           }
        }
     }

     private void OnPropertyChanged(PropertyChangedEventArgs e)
     {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, e);
     }
  }
}
+3
source share
1 answer

Works for me too! Environment - VS.Net 2008

, , , "Re-Building" "Build"?

0

Source: https://habr.com/ru/post/1795213/


All Articles