来自微软:“当基础列表更改或列表中的项发生更改时,就会发生BindingSource.ListChanged事件”。
但在我的例子中,事件会触发每个位置的变化。该表单有一个UserControl、一个BindingSource和一个按钮。
用户控件有一个TextBox和两个属性:
/// <summary>
/// Is working: ListChanged is not fired
/// </summary>
public override string Text
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
/// <summary>
/// Is not working: ListChanged is fired on Position changes
/// </summary>
public string MyProperty
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}表单上的按钮更改了BindingSource的位置:
void next_Click(object sender, EventArgs e)
{
bindingsource.Position += 1;
}当我使用"Text“属性绑定控件时,不会像预期的那样发生ListChanged事件:
myusercontrol1.DataBindings.Add("Text", bindingsource, "name");但是,当我使用"MyProperty“属性绑定控件时,ListChanged事件会触发位置更改:
myusercontrol1.DataBindings.Add("MyProperty", bindingsource, "name");我尝试了不同的DataSorces,如本例所示:
public Example()
{
InitializeComponent();
string xml = @"<states>"
+ @"<state><name>Washington</name></state>"
+ @"<state><name>Oregon</name></state>"
+ @"<state><name>Florida</name></state>"
+ @"</states>";
byte[] xmlBytes = Encoding.UTF8.GetBytes(xml);
MemoryStream stream = new MemoryStream(xmlBytes, false);
DataSet set = new DataSet();
set.ReadXml(stream);
bindingsource.DataSource = set;
bindingsource.DataMember = "state";
bindingsource.ListChanged += BindingNavigator_ListChanged;
myusercontrol1.DataBindings.Add("MyProperty", bindingsource, "name");
}如何使用MyProperty并避免在位置更改时触发ListChanged事件?为什么Text属性像预期的那样工作,但是MyProperty不工作呢?
谢谢你,克里斯蒂
发布于 2016-08-21 17:17:09
为什么文本属性按预期工作,而MyProperty却不工作?
都是关于变更通知的。您可能知道,Windows数据绑定支持两种类型的源对象更改通知--实现INotifyPropertyChanged或提供{PropertyName}Changed命名事件的对象。
现在看看您的用户控件。首先,它不实现INotifyPropertyChanged。但是,是一个名为TextChanged的事件,所以当数据绑定到Text属性时,BindingSource将使用该事件触发ListChanged。但是,当绑定到MyProperty时,由于没有名为MyPropertyChanged的事件,所以当Position (因此是当前对象)发生变化时,数据绑定基础结构将尝试用ListChanged事件来模拟它。
在此之后,将以下内容添加到用户控件中:
public event EventHandler MyPropertyChanged
{
add { textBox1.TextChanged += value; }
remove { textBox1.TextChanged -= value; }
}而绑定到您的属性的数据将按预期工作。
https://stackoverflow.com/questions/39066217
复制相似问题