Weronika
Weronika

Reputation: 35

nested xaml elements - rewrite it in code

I need to create a DataGridColumn from code. The XAML equivalent would be:

    <data:DataGridTemplateColumn Header="Name" Width="100">
        <data:DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}" TextTrimming="WordEllipsis"></TextBlock>
            </DataTemplate>
        </data:DataGridTemplateColumn.CellTemplate>
    </data:DataGridTemplateColumn>

I've started like that:

 DataGridTemplateColumn column = new DataGridTemplateColumn
   {
      Header = "Name",
      Width = 100,
   };

TextBlock inside =  new TextBlock {TextTrimming = TextTrimming.CharacterEllipsis};

But I don't know how to 'merge' such puzzles. There are nested elements in XAML, how to achieve this from code?

Upvotes: 2

Views: 508

Answers (2)

Stefan Dragnev
Stefan Dragnev

Reputation: 14473

A good way to do this is to pack the entire XAML snippet into a string and call XamlReader.Load() or XamlReader.Parse() on it. The bonus feature of this approach is that it'll work in Silverlight as well (with some fiddling), where you can't build DataTemplates in code.

Upvotes: 3

theChrisKent
theChrisKent

Reputation: 15099

Almost there, change your code to this and it should work:

DataGridTemplateColumn column = new DataGridTemplateColumn
   {
      Header = "Name",
      Width = 100,
   };
FrameworkElementFactory ftb = new FrameworkElementFactory(typeof(TextBlock));
Binding b = new Binding("Name");
ftb.SetValue(TextBlock.Text, b);
ftb.SetValue(TextBlock.TextTrimming, TextTrimming.CharacterEllipsis);    
DataTemplate ct = new DataTemplate();
ct.VisualTree = ftb;
column.CellTemplate = ct;

Another method besides the above is to define your datatemplate in XAML within your resources then dynamically load it in the code:

XAML:

<Window.Resources>
    <DataTemplate x:Key="myCellTemplate">
        <TextBlock Text="{Binding Name}" TextTrimming="WordEllipsis" />
    </DataTemplate>
</Window.Resources>

Code:

DataGridTemplateColumn column = new DataGridTemplateColumn
   {
      Header = "Name",
      Width = 100,
   };
column.CellTemplate = this.FindResource("myCellTemplate") as DataTemplate;

Upvotes: 2

Related Questions