Thursday, December 5, 2013

Creating XAML elements on the fly

Here is the code to create
1) GetFlagTypeColumn - It is a control which we can attach with image to display, for eg, Red image for NO and Green image for Yes
1) GetTextColumn - To create TextBlock
1) GetCheckboxColumn - To create Checkbox
Simlarly we can create other XAML controls.


private DataGridTemplateColumn GetFlagTypeColumn(string columnHeader, string columnName)
{

var templateColumn = new DataGridTemplateColumn();templateColumn.Header = columnHeader;
templateColumn.Width = 90d;

var layout = new DataTemplate();
var flagImage = new FrameworkElementFactory(typeof(Image));flagImage.SetValue(
Image.HorizontalAlignmentProperty, HorizontalAlignment.Center);flagImage.SetValue(
Image.VerticalAlignmentProperty, VerticalAlignment.Center);flagImage.SetValue(
Image.HeightProperty, 20d);flagImage.SetValue(
Image.WidthProperty, 20d);flagImage.SetBinding(
Image.SourceProperty, new Binding(columnName) { Converter = boolToImageConverter });layout.VisualTree = flagImage;
templateColumn.CellTemplate = layout;

return templateColumn;}

private DataGridTemplateColumn GetTextColumn(string columnHeader, string columnName){

var templateColumn = new DataGridTemplateColumn();templateColumn.Header = columnHeader;

var layout = new DataTemplate();
var entityElement = new FrameworkElementFactory(typeof(TextBlock));entityElement.SetBinding(
TextBlock.TextProperty, new Binding(columnName));layout.VisualTree = entityElement;
templateColumn.CellTemplate = layout;

return templateColumn;}

private DataGridTemplateColumn GetCheckboxColumn(string columnHeader, string columnName){

var templateColumn = new DataGridTemplateColumn();templateColumn.Header = columnHeader;

var layout = new DataTemplate();
var entityElement = new FrameworkElementFactory(typeof(CheckBox));
Binding b = new Binding();b.Path =
new PropertyPath(columnName);b.UpdateSourceTrigger =
UpdateSourceTrigger.PropertyChanged;b.Mode =
BindingMode.TwoWay;entityElement.SetBinding(
CheckBox.IsCheckedProperty, b);layout.VisualTree = entityElement;
templateColumn.CellTemplate = layout;

return templateColumn;}


Note: This is not my original work. Have blogged it here just for my future reference and of course if someone wants to use it.

No comments:

Post a Comment