2016-08-21 101 views
2

来自Microsoft: “BindingSource.ListChanged事件发生在底层列表更改或列表中的项目发生更改时”。BindingSource ListChanged事件触发位置更改

但在我的例子中,事件触发每个位置的变化。该表单有一个UserControl,一个BindingSource和一个按钮。

用户控制具有一个文本框和两个属性:当我结合使用的“文本”的控制

void next_Click(object sender, EventArgs e) 
{ 
    bindingsource.Position += 1; 
} 

/// <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的位置财产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不是?

由于提前, 克里斯蒂安

回答

1

为什么按预期工作文本属性,但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; } 
} 

和数据,预期结合,你的财产将正常工作。

+1

谢谢伊凡你的伟大答案! – Cristian