我有一个名为listInput
的列表,其中包含名为friends
的子列表:
List<Input> listInput=new List<Input>();
BindingList<Input> blInput;
BindingSource bsInput;
public class Input
{
public string Name { get; set; }
public List<Friend> friends{ get; set; }
}
public class Friend
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
我有两个DataGridView
(c#,winform),名为dgInput
,dgFriends
。 dgInput
像这样绑定到BindingList
:
blInput = new BindingList<Input>(listInput);
bsInput = new BindingSource(blInput, null);
dgInput.DataSource = bsInput;
用户更改dgInput
上的任何单元格后,dgInput
是可编辑和可更新运行时,现在的问题是:我如何将dgFriends
绑定到子列表friends
,如果选择dgInput
行更改,它将自动更改;非常重要的是,用户更改后dgFriens
将是(updatable)运行时更改dgFriends后,dgFriends
上的任何单元格(listInput
和子列表friends
必须更新)。谢谢大家。
这是一个简单的示例:
Name
属性的列表,它使用您定义的BindingSource。此BindingSource的DataSource设置为List<Input>
,并且其DataMember为空(或为null),因此它将使用Name
属性(不能将Name
设置为DataMember
,否则会得到一个结果是Char
的数组)。 friends
属性,该属性表示List<class>
对象。 这将在两个BindingSource对象之间生成一个活动绑定:当第一个BindingSource Current
对象更改时,第二个BindingSource将紧随其后。
两个类的所有属性都是可编辑的
注意:我已经在INotifyPropertyChanged类中实现了Input
接口,以通知Name
属性的更改:在这种情况下,它不是严格要求的(或者根本不需要),但是您可能希望在这里使用它,以后需要。
List<Input> listInput = new List<Input>();
BindingSource bsInput = null;
public SomeForm()
{
InitializeComponent();
bsInput = new BindingSource(listInput, "");
var bsFriends = new BindingSource(bsInput, "friends");
dataGridView1.DataSource = bsInput;
dataGridView2.DataSource = bsFriends;
}
public class Input : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string m_Name = string.Empty;
public string Name {
get => m_Name;
set { m_Name = value;
NotifyPropertyChanged(nameof(this.Name));
}
}
public List<Friend> friends { get; set; }
private void NotifyPropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public class Friend
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
这是它的工作方式:
示例对象初始化,用于测试:
listInput.AddRange(new[] {
new Input() {
Name = "Name One", friends = new List<Friend>() {
new Friend () { FirstName = "First", LastName = "Friend of One"},
new Friend () { FirstName = "Second", LastName = "Friend of One"},
new Friend () { FirstName = "Third", LastName = "Friend of One"},
}
},
new Input() {
Name = "Name Two",
friends = new List<Friend>() {
new Friend () { FirstName = "First", LastName = "Friend of Two"},
new Friend () { FirstName = "Second", LastName = "Friend of Two"},
new Friend () { FirstName = "Third", LastName = "Friend of Two"},
}
},
new Input() {
Name = "Name Three",
friends = new List<Friend>() {
new Friend () { FirstName = "First", LastName = "Friend of Three"},
new Friend () { FirstName = "Second", LastName = "Friend of Three"},
new Friend () { FirstName = "Third", LastName = "Friend of Three"},
}
}
});