There are 3 main components to achieving this functionality:
- Create an Class to hold your objects
- Create an Observable Collection
- Bind the Collection in your XAML
Our first step will be to create the DataGrid, we'll be using Name and Age as two columns in the DataGrid
<sdk:DataGrid x:Name="listView" Margin="137,107,172,171">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Binding="{x:Null}" CanUserSort="True" CanUserReorder="True" CellStyle="{x:Null}" CanUserResize="True" ClipboardContentBinding="{x:Null}" DisplayIndex="-1" DragIndicatorStyle="{x:Null}" EditingElementStyle="{x:Null}" ElementStyle="{x:Null}" Foreground="{x:Null}" FontWeight="Normal" FontStyle="Normal" FontSize="NaN" HeaderStyle="{x:Null}" Header="Name" IsReadOnly="False" MaxWidth="Infinity" MinWidth="0" SortMemberPath="{x:Null}" Visibility="Visible" Width="Auto"/>
<sdk:DataGridTextColumn Binding="{x:Null}" CanUserSort="True" CanUserReorder="True" CellStyle="{x:Null}" CanUserResize="True" ClipboardContentBinding="{x:Null}" DisplayIndex="-1" DragIndicatorStyle="{x:Null}" EditingElementStyle="{x:Null}" ElementStyle="{x:Null}" Foreground="{x:Null}" FontWeight="Normal" FontStyle="Normal" FontSize="NaN" HeaderStyle="{x:Null}" Header="Age" IsReadOnly="False" MaxWidth="Infinity" MinWidth="0" SortMemberPath="{x:Null}" Visibility="Visible" Width="Auto"/>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
As you can see the code above outputs something like this:
Now you want to get some data in there, but you don't want to give it rows through the interface, you want to make sure that it can populate, remove or rearrange values from code.
If you look into the top area of your XAML you'll notice that there's a header that looks similar to the below
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="Demo.MainPage" Width="640" Height="480">
What you need to do is just before the "> you need to add a data context binding DataContext="{Binding RelativeSource={RelativeSource Self}}">, this will allow your interface and code to be able to interact with each other. The final look of your header will be
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
x:Class="test.MainPage"
Width="640" Height="480"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
Now that the XAML is all set up for now, let's get to the not so trivial part, the C# Code.
In the C# Code you will need to create a class, below is a class that will be used to house all the properties (Name and Gender) for the Collection to access.
User.cs
namespace Demo
{
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
}
Once the User class has been created we need to create an observable collection in our main code, so open up the MainPage.xaml.cs file and replicate the following:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace Demo
{
public partial class MainPage : UserControl
{
// Create an ObservableCollection Object with the User Type
ObservableCollection _users = new ObservableCollection();
// "Constructor" for Users
public ObservableCollection Users
{
get { return _users; }
}
public MainPage()
{
// Required to initialize variables
InitializeComponent();
// Create a test user
Users.Add(new User{ Name = "Sinvise", Age = 10});
}
}
}
So what have we done here
- Created an ObservableCollection Object
- Created a method that will be used for the binding
- Populate the Collection with a user
For that you'll need to go back to the XAML, and make the following changes to your DataGrid
<sdk:DataGrid x:Name="listView" Margin="137,107,172,171" ItemsSource="{Binding Path=UserCollection}"/>
As you can see, the whole DataGrid has been stripped down and an ItemsSource binding has been placed instead.
Now when you run the program you get the following
And that's it! You have a full working binding to an ObservableCollection that will allow you to manipulate a DataGrid or a ListView how you want.
Listed below is extra code that will provide extra functionality; Add, Remove and move items.
User.cs - Extra Methods
/// <summary>
/// Add a User to the collection
/// </summary>
/// <param name="name"></param>
/// <param name="age"></param>
private void Add(string name, int age)
{
_userCollection.Add(new User{ Name = name, Age = age});
}
/// <summary>
/// Remove the selected user from the collection
/// </summary>
private void Remove()
{
if(_userCollection.Count > 0)
{
_userCollection.RemoveAt(listView.SelectedIndex);
}
else
{
MessageBox.Show("No Tasks");
}
}
/// <summary>
/// Move the selected user up in the list
/// </summary>
private void MoveItemUp()
{
if (_userCollection.Count > 1)
{
int selected = listView.SelectedIndex;
int newIndex = listView.SelectedIndex - 1;
_userCollection.Move(selected, newIndex);
}
}
/// <summary>
/// Move the selected user down in the list
/// </summary>
private void MoveItemDown()
{
if (_userCollection.Count > 1)
{
int selected = listView.SelectedIndex;
int newIndex = listView.SelectedIndex + 1;
_userCollection.Move(selected, newIndex);
}
}
Please leave a comment if you feel that you can help add to this tutorial.