Datagrid binding in WPF
I know this has been asked already but I have done almost everything what is suggested by developers.
<DataGrid x:Name="Imported" VerticalAlignment="Top"
DataContext="{Binding Source=list}"
AutoGenerateColumns="False" CanUserResizeColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Path=ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Path=Date}"/>
</DataGrid.Columns>
</DataGrid>
I am trying to show this in modal dialog box and populating the license list in the constructor of the modal dialog box.
But still nothing is getting populated inside the DataGrid
.
Constructor code:
public diagboxclass()
{
List<object> list = new List<object>();
list = GetObjectList();
}
public class object
{
string id;
DateTime date;
public string ID
{
get { return id; }
set { id = value; }
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
}
Do you guys think something to do with the object list?
PLEASE do not use object as a class name:
public class MyObject //better to choose an appropriate name
{
string id;
DateTime date;
public string ID
{
get { return id; }
set { id = value; }
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
}
You should implement INotifyPropertyChanged
for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.
Your Viewmodel class/ dialogbox class should have a Property
of your MyObject
list. ObservableCollection<MyObject>
is the way to go:
public ObservableCollection<MyObject> MyList
{
get...
set...
}
In your xaml
you should set the Itemssource
to your collection of MyObject
. (the Datacontext
have to be your dialogbox class!)
<DataGrid ItemsSource="{Binding Source=MyList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
</DataGrid.Columns>
</DataGrid>
Without seeing said object list, I believe you should be binding to the DataGrid
's ItemsSource
property, not its DataContext
.
<DataGrid x:Name="Imported" VerticalAlignment="Top"
ItemsSource="{Binding Source=list}"
AutoGenerateColumns="False" CanUserResizeColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
</DataGrid.Columns>
</DataGrid>
(This assumes that the element [UserControl
, etc.] that contains the DataGrid
has its DataContext
bound to an object that contains the list
collection. The DataGrid
is derived from ItemsControl
, which relies on its ItemsSource
property to define the collection it binds its rows to. Hence, if list
isn't a property of an object bound to your control's DataContext
, you might need to set both DataContext={Binding list}
and ItemsSource={Binding list}
on the DataGrid
).