UserControl中的DataBinding在设计时不起作用?

时间:2011-02-28 13:01:19

标签: c# data-binding user-controls inotifypropertychanged

我对数据绑定和用户控制有一个小问题。

我构建(使用C#2010)用户控件,它基本上是ComboBox的包装器,它有一个自定义属性,当更改时,设置ComboBox的值。相反,如果ComboBox中的选定项发生更改,则属性的值将更改。

现在,我可以通过在ComboBox上捕获“selected selected changed”事件并设置属性来实现这一点,我可以在属性设置器中设置ComboBox的选定值,但我猜测我也可能能用DataBinding做到这一点。

它几乎可以工作,但并不完全。

它在运行时工作,但不是在设计时,我想知道这是否可以轻松解决。

例如,如果在设计时,我选择了我的用户控件的实例,并从属性窗口中选择我的控件的自定义属性,并更改它,ComboBox不会反映更改。

任何指向我错过的东西的指针都会受到极大的欢迎。显然,我可以设置ComboBox选择的值,但如果DataBinding会为我做这件事会很好。

谢谢,
罗斯

(这是我的用户控件。在表单上删除一个并使用IDE更改“位置”属性)

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

1 个答案:

答案 0 :(得分:0)

也适合我! 环境 - VS .Net 2008

我认为只有差异可能是'重建'应用程序而不仅仅是'构建'?