Search This Blog

Friday, October 28, 2011

Silverlight DataGrid dynamic binding in DataGridTemplateColumn

The problem is that we want to bind a field from a custom object. This field is of type different from string (we could use DataGridTextColumn and set its binding like this:

DataGridColumns.Add(new DataGridTextColumn());
((DataGridBoundColumn) DataGridColumns[DataGridColumns.Count - 1]).Binding = new Binding() {Path = new PropertyPath("A")};    )

The only other Column type in SL4 is DataGridTemplateColumn. So we have to create a template, insert a TextBox into it and bind its text to our property. The solution looks as follows:

 

DataGridColumns.Add(new DataGridTemplateColumn());
string templateString = "<DataTemplate x:Key=\"CustomDataGridColumnTemplate\" "
    + "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"  "
    + "xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" >"
    + "<TextBox Name=\"CustomTextBox\" Text=\"{Binding [0]}\" />"
    + "</DataTemplate>";
templateString = templateString.Replace("[0]", "A");
DataTemplate mycolumntemplate = XamlReader.Load(templateString) as DataTemplate;
((DataGridTemplateColumn) DataGridColumns[DataGridColumns.Count - 1]).CellTemplate = mycolumntemplate;
DataGridColumns[DataGridColumns.Count - 1].Header = browserColumn.Name;
DataGridColumns[DataGridColumns.Count - 1].Width = DataGridLength.Auto;

 

Note: You don’t need to include any namespaces if you don’t use x:Name etc.

1 comment:

  1. Thanks, this helped with something I was working on!

    ReplyDelete

If you like this post, please leave a comment :)