none
Can i create DataTemplate in code-behind?

    Question

  • Normally I can create DataTemplate by XAML code but i cannot find the way to create DataTemplate in code-behind. Is it possible? Someone has worked on this/?
    Thursday, May 04, 2006 7:02 AM

Answers

  • This should work. Havent tried it though.

    FrameworkElementFactory fef = new FrameworkElementFactory(typeof(TextBlock));

    Binding placeBinding = new Binding();

    fef.SetBinding(TextBlock.TextProperty, placeBinding);

    placeBinding.Path = new PropertyPath("Name");

    dataTemplate = new DataTemplate();

    dataTemplate.VisualTree = fef;

    Thursday, May 04, 2006 6:08 PM
    Moderator

All replies

  • This should work. Havent tried it though.

    FrameworkElementFactory fef = new FrameworkElementFactory(typeof(TextBlock));

    Binding placeBinding = new Binding();

    fef.SetBinding(TextBlock.TextProperty, placeBinding);

    placeBinding.Path = new PropertyPath("Name");

    dataTemplate = new DataTemplate();

    dataTemplate.VisualTree = fef;

    Thursday, May 04, 2006 6:08 PM
    Moderator
  • Thanks so much! It's working fine. Great!
    Friday, May 05, 2006 2:38 AM
  • This example seems to show the Name-property of an object.
    Could you extract values based on other things then the names of properties?

    If, for example, you have a IList<String> and wishes to concatenate all strings on an even index, can you do that?
    I feel that you now have left the abilities of PropertyPath. But if anyone knows how to do it, it would be nice.

    That way you could receive a template from an external source (say a database) and format your data using that.

    Or is there any way to add a "custom formatter" to a Framework object? Implement some interface so that some method like "FrameworkObject Format(object)" should be called. That way you can format anything to any arbitary thing.

    Cheers!
    Monday, May 28, 2007 4:50 PM
  • Hello

    To bind a string property to something else than a string source, you need to convert each source value to a string using a converters.

    Suppose you have a List<string> provider like the following foo class

    using System.Collections.Generic;

     

    namespace ConverterSample {

      public class ObjectWithAList {

        public List<string> ListProperty {

          get {

            return new List<string>(new string[] {"Oh", "my!", "This", "is", "very", "easy!"});

          }

        }

      }

    }

    To show the elements of the list inside a TextBlock, separated by commas you can create a class implementing interface IValueConverter:

    using System;

    using System.Collections;

    using System.Globalization;

    using System.Windows.Data;

     

    namespace ConverterSample {

      public class ListToStringConverter : IValueConverter {

        public object Convert(object value, Type targetType, object parameter,

                              CultureInfo culture) {

          IEnumerable list = value as IEnumerable;

          if (list == null) return null;

          if (targetType != typeof(string)) return false;

          string result = "";

          foreach (object o in list) {

            if (result.Length > 0) result += ", "; // separator

            result += System.Convert.ToString(o, culture);

          }

          return result;

        }

     

        public object ConvertBack(object value, Type targetType, object parameter,

                                  CultureInfo culture) {

          throw new NotImplementedException();

        }

      }

    }

      

    Then to do the binding, put instances of both classes inside a window:

    <Window x:Class="ConverterSample.Window1"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:myapp="clr-namespace:ConverterSample"

        Title="ConverterSample" Height="300" Width="300"

        >

      <Window.Resources>

        <myappSurprisebjectWithAList x:Key="obj"/>

        <myapp:ListToStringConverter x:Key="listConverter"/>

      </Window.Resources>

        <Grid DataContext="{StaticResource obj}">

          <TextBlock Text="{Binding ListProperty, Converter={StaticResource listConverter}}"/>

        </Grid>

    </Window>

     

    Bye folks ...

    Monday, May 28, 2007 7:12 PM
  • Hello

    To bind a string property to something else than a string source, you need to convert each source value to a string using a converters.

    Suppose you have a List<string> provider like the following foo class

    using System.Collections.Generic;

     

    namespace ConverterSample {

      public class ObjectWithAList {

        public List<string> ListProperty {

          get {

            return new List<string>(new string[] {"Oh", "my!", "This", "is", "very", "easy!"});

          }

        }

      }

    }

    To show the elements of the list inside a TextBlock, separated by commas you can create a class implementing interface IValueConverter:

    using System;

    using System.Collections;

    using System.Globalization;

    using System.Windows.Data;

     

    namespace ConverterSample {

      public class ListToStringConverter : IValueConverter {

        public object Convert(object value, Type targetType, object parameter,

                              CultureInfo culture) {

          IEnumerable list = value as IEnumerable;

          if (list == null) return null;

          if (targetType != typeof(string)) return false;

          string result = "";

          foreach (object o in list) {

            if (result.Length > 0) result += ", "; // separator

            result += System.Convert.ToString(o, culture);

          }

          return result;

        }

     

        public object ConvertBack(object value, Type targetType, object parameter,

                                  CultureInfo culture) {

          throw new NotImplementedException();

        }

      }

    }

      

    Then to do the binding, put instances of both classes inside a window:

    <Window x:Class="ConverterSample.Window1"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:myapp="clr-namespace:ConverterSample"

        Title="ConverterSample" Height="300" Width="300"

        >

      <Window.Resources>

        <myappSurprisebjectWithAList x:Key="obj"/>

        <myapp:ListToStringConverter x:Key="listConverter"/>

      </Window.Resources>

        <Grid DataContext="{StaticResource obj}">

          <TextBlock Text="{Binding ListProperty, Converter={StaticResource listConverter}}"/>

        </Grid>

    </Window>

     

    Bye folks ...

    Monday, May 28, 2007 7:20 PM
  • Sweet!

    However, this way you can only convert to a string.
    I was thinking to convert it into, say a listview-grid row, or perhaps a tree structure.
    Would that be possible?

    Or would you have to, dynamically in code-behind, create a DataTemplate?

    Cheers!
    Tuesday, May 29, 2007 9:22 AM
  • How Can I add a GRID definition in the DataTemplate in code-behind? I am able to create it in XAML , I want to write code in C# for it. I have created the GRID definition successfully but not able to add the GRID as a child to DataTemplate. Thanks in Advance

    <DataTemplate x:Name="datatemp" >

    <Grid ShowGridLines="True" Name="main" >

    <Grid.ColumnDefinitions>

    <ColumnDefinition SharedSizeGroup="FirstName"/>

    <ColumnDefinition SharedSizeGroup="SplitterName"/>

    <ColumnDefinition   />

    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>

    <RowDefinition />

    </Grid.RowDefinitions>

    <TextBlock Grid.Row="0" Grid.Column="0" Name="txt" TextWrapping="Wrap" Text="{Binding Path=Rank}"/>

    <GridSplitter Grid.Row="0" Grid.Column="1" ResizeBehavior="PreviousAndNext" />

    <TextBlock Grid.Row="0" Grid.Column="2" TextWrapping="Wrap" Text="{Binding Path=Name}" />

    </Grid>

    </DataTemplate>

     

    Monday, October 29, 2007 6:59 AM
  • Anyone found a solution for this?

    I got the same problem as VarunK. I already build the Grid in code-behind but now I would like to assign it to a DataTemplate so I can use it as a ItemTemplate of my ComboBox.

     

    Phil

     

    Monday, December 17, 2007 7:32 AM
  • I've been fighting the same problem for a while.

     

    Best solution I've found:

     

    Create the template in XAML (Window.Resources or UserControl.Resources)

     

    Then assign it to the Gridview in code using

    FindResource("yourKey").

    http://msdn2.microsoft.com/en-us/library/ms752326.aspx

    Friday, April 11, 2008 8:49 AM
  • I've managed to add a stack panel using this simple code:

    FrameworkElementFactory stackPanel = new FrameworkElementFactory(typeof(StackPanel));
                foreach (DataGridBoundColumn dgColumn in entity.CustomColumns.Cast<DataGridBoundColumn>())
                {
                    FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));
                    textBlock.SetBinding(TextBlock.TextProperty, dgColumn.DataFieldBinding);
                    stackPanel.AppendChild(textBlock);
                }

    DataTemplate result = new DataTemplate()
    result.VisualTree = stackPanel

    "ME: How do I achive the imposible !" "The Wise Man: With entusiams !"
    Wednesday, October 08, 2008 9:49 AM