动态添加列和行到 wpf listview
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16934944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add columns and rows to wpf listview dynamically
提问by ooorndtski
i want to add new columns and rows to a C# WPF ListView (GridView) at runtime. As far as i know you can only add rows to a gridview by using anonymous objects or classes with a static set of members to which the columns are bound. Is there a way to do this at runtime that the user is able to add a new column, bind this column to something and add new data?
我想在运行时向 C# WPF ListView (GridView) 添加新的列和行。据我所知,您只能通过使用匿名对象或类与列绑定到的静态成员集来向 gridview 添加行。有没有办法在运行时做到这一点,用户可以添加一个新列,将此列绑定到某物并添加新数据?
thx ooorndtski
谢谢 ooorndtski
回答by nvoigt
Yes, you can do this in code an runtime. You need the GridView as a variable (give it a name in XAML to auto-generate that variable in Visual Studio). The GridView has a Columnsproperty that you can handle like any other collection, you can add and remove for example.
是的,您可以在运行时代码中执行此操作。您需要将 GridView 作为变量(在 XAML 中为其命名以在 Visual Studio 中自动生成该变量)。GridView 有一个Columns属性,您可以像处理任何其他集合一样处理它,例如,您可以添加和删除它。
This is the example from MSDN (The gridview name "myGridView"):
这是来自 MSDN 的示例(gridview 名称“myGridView”):
GridViewColumn gvc3 = new GridViewColumn();
gvc3.DisplayMemberBinding = new Binding("EmployeeNumber");
gvc3.Header = "Employee No.";
gvc3.Width = 100;
myGridView.Columns.Add(gvc3);
Generally speaking, anything you can do in XAML, you can do in code.
一般来说,您可以在 XAML 中执行的任何操作,也可以在代码中执行。
回答by ooorndtski
So, what i was looking for is described in this thread. He creates a new Dictionary-class, which implements the INotifyPropertyChangedinterface. When adding data to the dictionary an event is triggered.
所以,我正在寻找的内容在此线程中进行了描述。他创建了一个新的 Dictionary 类,它实现了INotifyPropertyChanged接口。将数据添加到字典时会触发一个事件。
At the place in your code where you want to add a new row, you just put the data into an object of this Dictionary class and add the Dictionary to an ObservableCollection which is bound to the DataGrid.
在代码中要添加新行的位置,您只需将数据放入此 Dictionary 类的对象中,然后将 Dictionary 添加到绑定到 DataGrid 的 ObservableCollection 中。

