Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a wpf datagrid without binding to anything?

Tags:

c#

wpf

datagrid

I want to create a datagrid without binding to anything. User can add/delete/edit data and the code will collect the data programatically. I did the following but the grid does not allow me to add new row.

<DataGrid Name="dgData" CanUserAddRows="True" MinHeight="100">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Column1"></DataGridTextColumn>
                <DataGridTextColumn Header="Column2"></DataGridTextColumn>
            </DataGrid.Columns>
</DataGrid>

When I run the application, the grid is shown with only headers. Unlike winform DataGridView that gives an empty first row. There is no way I can add a new row on the GUI.

like image 793
Ryan Avatar asked Oct 05 '22 02:10

Ryan


2 Answers

You still need to set (or bind) the ItemsSource to an empty collection that supports adding (implements IList), also you should bind the columns to properties of the item datatype (or let the DataGrid create them for you), otherwise they won't show anything.

like image 97
H.B. Avatar answered Oct 23 '22 10:10

H.B.


I know my answer is pretty late, but someone might still come here and benift from it. So basically I did not find a way to fill the DataGrid without Binding in WPF but I found a way to make binding with an anonymous type with dynamically named object properties.

List<object> myList = new List<object>();
dynamic obj = new ExpandoObject();
((IDictionary<String, Object>)obj)["PropertyName"] = "PropertyValue";
myList.Add(obj);
MyDataGrid.ItemsSource = myList;
like image 1
Zeyad Avatar answered Oct 23 '22 12:10

Zeyad