试试这个:
ItemsSource="{Binding ElementName=window1, Path=Users, Mode=TwoWay}" MouseDoubleClick="listViewUsers_MouseDoubleClick">
其中ItemsSource =“{Binding ElementName = window1,Path = Users,Mode = TwoWay}”
> ElementName是XAML中Window的名称(只需将x:Name =“window1”添加到Window标记中,就像使用任何其他ontrol一样.
>用户是List,应该与Dictionary一样
> Mode = TwoWay意味着如果网格被修改,列表也会被修改,反之亦然(双向绑定)
编辑:
试试这个:
XAML:
C#:
public class TheClass
{
public int Col1, Col2, Col3;
public Dictionary otherColumns = new Dictionary();
}
public class OtherColumns
{
public string ColumnName;
public int Value;
}
并在Window_Loaded下调用此方法:
private void PopulateListView()
{
TheClass c = new TheClass();
c.Col1 = 10;
c.Col2 = 20;
c.Col3 = 30;
c.otherColumns.Add(0, new OtherColumns() { ColumnName = "Col4", Value = 40 });
c.otherColumns.Add(1, new OtherColumns() { ColumnName = "Col5", Value = 50 });
c.otherColumns.Add(3, new OtherColumns() { ColumnName = "Col6", Value = 60 });
DataTable table = new DataTable();
// adding regular columns
table.Columns.Add("Col1", typeof(int));
table.Columns.Add("Col2", typeof(int));
table.Columns.Add("Col3", typeof(int));
// adding dynamic columns
foreach (KeyValuePair pair in c.otherColumns)
{
table.Columns.Add(pair.Value.ColumnName, typeof(int));
}
DataRow row = table.NewRow();
// adding regular column values to the DataTable
row["Col1"] = c.Col1;
row["Col2"] = c.Col2;
row["Col3"] = c.Col3;
// adding dynamic column values to the DataTable
foreach (KeyValuePair pair in c.otherColumns)
{
row[pair.Value.ColumnName] = pair.Value.Value;
}
table.Rows.Add(row);
// Start binding the table.
gridViewTest.Columns.Clear();
System.Windows.Controls.GridViewColumn gvc;
Binding binding;
foreach (DataColumn column in table.Columns)
{
gvc = new System.Windows.Controls.GridViewColumn();
binding = new System.Windows.Data.Binding();
binding.Path = new PropertyPath(column.ColumnName);
binding.Mode = BindingMode.OneWay;
gvc.Header = column.Caption;
gvc.DisplayMemberBinding = binding;
gridViewTest.Columns.Add(gvc);
}
listViewTest.DataContext = table;
}
我不是说这是最好的解决方案,但它可以提供帮助.让我知道.