locked
binding to datatemplate from class RRS feed

  • Question

  • I have a regular class (not SilverlightControl) which is creating some UserControls. In that class I want to get a DataTemplate from AppResources.. this works.. but I can't figure out how to get the binding to work..I don't know how to set "Name"

    DataTemplate dt = (DataTemplate)Application.Current.Resources["test"];

    <Application.Resources>
        <DataTemplate x:Key="test">
           <StackPanel Orientation="Horizontal">
              <TextBlock x:Name="myText" Text="{Binding Name}" />
              <Button Content="x" Margin="2" />
           </StackPanel>
       </DataTemplate>
    </Application.Resources>

     

     on a side note.. i did get it to work this way.. but creating the xaml in the app.xaml seems much cleaner.

    public static DataTemplate CreateDTfromXaml(string Name)

    {

    return (DataTemplate)XamlReader.Load(@"<DataTemplate

    xmlns=""http://schemas.microsoft.com/client/2007"">

    <StackPanel Orientation=""Horizontal"">

    <TextBlock Text="""
    + Name + @"""/>

    <Button Content=""x"" Height=""20"" Margin=""2"" /> </StackPanel>

    </DataTemplate>"
    );

    }

     

     

    Thursday, June 11, 2009 12:32 PM

Answers

  • Which Control are you trying to use the DataTemplate on?

    If you are setting the ItemTemplate for something like ListBox, all you have to do is set the ItemsSource property to the collection of objects that has the Name property to bind to.

    e.g.

    public class ExampleObject

    {

          public string Name;

    }

    ...

    List<ExampleObject> sampleList = new List<ExampleObject>();

    sampleList.Add(new ExampleObject {Name="Test1"});

    sampleList.Add(new ExampleObject {Name="Test2"});

    ...

    ListBox list = new ListBox();

    list.ItemTemplate = (DataTemplate)Application.Current.Resources["Test"];

    list.ItemSouce = sampleList;

    Friday, June 12, 2009 11:45 AM