如何在C#中绑定两个类的变量?

时间:2016-06-02 07:48:52

标签: c# list binding two-way

我在C#中有两个类似的类

public class Property
{
    public string version;               
    public string CCodeName { get; set; }
    public string CDoc { get; set; }
    public string ShortName { get; set; }
}

public class PropertyFieldsInExcel
{
    public string ShortNames { get; set; }
    public string CNames { get; set; }
    public string CDoc { get; set; }
    public string Version { get; set; }        
}   

在此之后我创建了两个列表。

static List<PropertyFieldsInExcel> listA = new List<PropertyFieldsInExcel>();
public List<Property> listB = new List<Property>();

现在,我想在这两个列表之间进行双向绑定。就像在listA中某些内容发生变化时,listB中的相应元素必须得到更新。

与if listA[i].ShortName = "abc"一样,listB[i].ShortName也必须具有相同的值。 listA.Add()应触发listB.Add(),反之亦然。

谢谢!

2 个答案:

答案 0 :(得分:2)

像@Amir所说,你必须实现INotifyPropertyChanged类,

,您的案例就是:INotifyPropertyChanged

的确切示例

你应该尝试这个例子。

答案 1 :(得分:-1)

在您的类中实现System.ComponentModel.INotifyPropertyChanged - 接口,并使用PropertyChanged事件处理程序在您的类中进行相应的更改。 使用System.Collections.ObjectModel.ObservableCollection<>代替列表。