我有一個關於數據綁定和用戶控件的小問題。UserControl內的DataBinding在設計時不起作用?
我構建了(使用C#2010)一個基本上是ComboBox的包裝的用戶控件,它有一個自定義屬性,當它改變時,它設置ComboBox的值。相反,如果組合框中的選定項目發生更改,則該屬性的值會更改。現在,我可以通過捕獲組合框上的「selected value changed」事件並設置屬性,並且我可以在屬性設置器中設置組合框的選定值,但我推測我可能會也可以用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);
}
}
}
我刪除了我的答案,因爲當我嘗試使用您的代碼時,它將它轉換爲您想要的方式工作(在設計時更改屬性時更新了組合框)。所以一定還有其他的事情要做。 – 2011-03-01 07:18:20
嗨,這很奇怪,因爲我剛剛做到這一點:打開VS,新的Windows項目,添加新的用戶控件,替換上面的代碼,在用戶控件上放置std組合框控件,在窗體上創建,刪除用戶控件,更改「位置「屬性」窗口中,顯示的用戶控件仍顯示「未知」。 – 2011-03-01 08:37:34