dotnet thoughts 

a dotnet developer's technical blog

Working with datagridview in WPF

When I started working in WPF, the issue found in WPF is that there is no DataGrid. And I couldn’t find any alternative for that. But after few days one of my colleague said there is an option to do it. And it is like setting a View of the Listview control.

So here is the XAML code for a grid like this

<listview Name="MyListView">
</listview><listview .ItemsSource>
<binding Source="{StaticResource AddressData}" Mode="OneWay" />
</listview>
<listview .View>
<gridview AllowsColumnReorder="True">
<gridviewcolumn Header="Name" Width="175" >
</gridviewcolumn><gridviewcolumn .DisplayMemberBinding>
<binding Path="Name" />
</gridviewcolumn>

<gridviewcolumn Header="Address" Width="200">
</gridviewcolumn><gridviewcolumn .DisplayMemberBinding>
<binding Path="Address" />
</gridviewcolumn>

<gridviewcolumn Header="Email" Width="100">
</gridviewcolumn><gridviewcolumn .DisplayMemberBinding>
<binding Path="Email" />
</gridviewcolumn>

</gridview>
</listview>

You can also use the “GridViewColumn.CellTemplate” for modifing the display of the controls. Here I am displaying a checkbox, using a “IsUserExists” boolean property.

<gridviewcolumn Header="?" Width="Auto" >
</gridviewcolumn><gridviewcolumn .CellTemplate>
<datatemplate>
<checkbox IsChecked="{Binding Path=IsUserExists}" />
</datatemplate>
</gridviewcolumn>

You can also create events too, like this

<style x:Key="ListViewItemEvent" TargetType="{x:Type ListViewItem}">
<eventsetter Event="MouseDoubleClick" Handler="lstvMouseDoubleClickEvent" />
</style>

And assign the “ListViewItemEvent” style to the ItemStyle property of the listview. And in the code you will get the ListviewItem object as sender.

Sub lstvMouseDoubleClickEvent(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
Dim oListViewItem As ListViewItem = CType(sender, ListViewItem)
Dim oAddress As Address = CType(oListViewItem.Content, Address)
'Binding code...
End Sub

I got the code of event setting from here