Simple Datagrid example?

Jun 5, 2009 at 4:10 PM
Edited Jun 5, 2009 at 4:13 PM

Hello all,

I've been searching for a real simple datagrid example of binding to a List<string> object.
I havent seen anything yet, I tried doing this:

Code:
List
<string> types = new List<string>();
types.Add("Specific Dates");
types.Add("Recurring Week Days");
types.Add("Day of Month");
gridTypes.ItemsSource = types;

XAML:
<toolkit:DataGrid Name="gridTypes" CanUserResizeRows="False" Grid.RowSpan="5" MinRowHeight="20" RowHeight="20" HeadersVisibility="None" Width="100" GridLinesVisibility="None">
 <toolkit:DataGrid.RowBackground>
  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
   <GradientStop Color="#FFFF0000" Offset="0"/>
   <GradientStop Color="#FF000000" Offset="1"/>
  </LinearGradientBrush>
 </toolkit:DataGrid.RowBackground>
</toolkit:DataGrid>

 

But that only results in displaying numbers in the cells. 14, 19 and 12
I have also tried adding in items using the Items.Add("text here") but that doesn't even display anything, as well as creating a DataTemplate, but that just errors out. I'm pretty sure that I'm missing something simple.
Could anybody please help with this? I think it would be good to have a real simple and easy example of doing something like this.

Thanks in advance,
Ed

Jun 5, 2009 at 5:04 PM

Ed,

14, 19, and 12 are the lengths of the strings that you've added to your List!  Since Length is the only public property exposed by string, this is why you are seeing this.  If you set HeadersVisibility="Column", you will see the column name.  Instead you should create an object that represents your data:

    public class Thing
    {
        public string Name { get; set; }
        public string Color { get; set; }
        public bool IsHairy { get; set; }
    }

Then create a list of these and bind it to your grid:

            List<Thing> things = new List<Thing>();
            things.Add(new Thing() { Name = "Water Bottle", Color = "Blue", IsHairy = false });
            things.Add(new Thing() { Name = "Hamster", Color = "Tan", IsHairy = true });
            things.Add(new Thing() { Name = "Cell Phone", Color = "Black", IsHairy = false });
            things.Add(new Thing() { Name = "Hammer", Color = "Silver", IsHairy = false });
            gridTypes.ItemsSource = things;

Make sure you look into implementing the INotifyPropertyChanged interface on your object and using an ObservableCollection.  By doing so, you can achieve two-way data binding.  So when you change a property value or add an item to the collection, it gets reflected in the grid.  And likewise when you edit an item in the grid, it gets reflected in the item in your collection. Dreamy!

Thanks,
Jad

Jun 5, 2009 at 5:18 PM

That worked great.
I didn't even need to change the XAML :)