Search code examples
c#wpfxamltelerikdatatemplate

Add DataTemplate to grid programmatically


I'm using Telerik Grid in my WPF application. If I define everything in XAML, it works fine, also the image column:

 <!-- IsActiveGroup -->
 <telerik:GridViewDataColumn DataMemberBinding="{Binding IsActiveGroup}" Width="45">
      <telerik:GridViewDataColumn.Header>
           <TextBlock Text="Column name" ToolTip="Some tooltip"/>
      </telerik:GridViewDataColumn.Header>
      <telerik:GridViewDataColumn.CellTemplate>
           <DataTemplate>
                <Image Source="{Binding Path=IsActiveImageSource, Converter={StaticResource imgConverter}}" Stretch="UniformToFill" RenderOptions.BitmapScalingMode="HighQuality" Width="20" Height="20" ToolTip="{Binding IsActiveGroup}" />
           </DataTemplate>
      </telerik:GridViewDataColumn.CellTemplate>
 </telerik:GridViewDataColumn>   

However, I have to do this programmatically, but I don't know how this can be done. I tried:

 var column = new GridViewDataColumn();    
 column.UniqueName = uniqueName;
 var headerTextBlock = new TextBlock();
 headerTextBlock.Text = headerText;
 headerTextBlock.ToolTip = headerTooltip;
 column.Header = headerTextBlock;

 var factory = new FrameworkElementFactory(typeof(Image));
 factory.SetValue(Image.SourceProperty, new Binding("IsActiveImageSource")
         {
            Converter = new BinaryImageConverter()
         });
 factory.SetValue(Image.StretchProperty, Stretch.UniformToFill);
 var cellTemplate = new DataTemplate() { VisualTree = factory };
 column.CellTemplate = cellTemplate;
 this.gridView.Columns.Add(column);

But this is not doing anything and I also don't know how to set the RenderOptions.

Can anyone help?

Thanks!


Solution

  • I think you forgot to load the template:

     factory.SetValue(Image.StretchProperty, Stretch.UniformToFill);
     var cellTemplate = new DataTemplate() { VisualTree = factory };
     cellTemplate.LoadContent();
     column.CellTemplate = cellTemplate;
     this.gridView.Columns.Add(column);
    

    If you want to assign it a DataContext do ite after loading the DataTemplate:

    cellTemplate.LoadContent();
    cellTemplate.DataContext = YourDataContext;
    

    Hope it helps!