tags:

views:

31

answers:

1

Hey

I have a data layer which is returning lists of classes containing data. I want to display this data in my form in WPF. The data is just properties on the class such as Class.ID, Class.Name, Class.Description (for the sake of example)

How can i create a custom control or template an existing control so that it can be given one of these classes and display its data in a data-bound fashion.

Thanks :)

+2  A: 

You could use a ListBox and set its ItemsSource property to the list containing your data items. Then you define a DataTemplate for your type like this:

<DataTemplate x:Key="MyDataTemplate" DataType="{x:Type MyType}">
    <StackPanel>
        <TextBlock Text="{Binding ID}"/>
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding Description}"/>
    </StackPanel>
</DataTemplate>

...and tell the ListBox to use this DataTemplate by setting the ItemTemplate property.

It is also sufficient to just define the DataTemplate as above and give it no key. Then it will be used for all items which have the respective type.

BTW: You can find a more detailed example in MSDN on the page for the ItemTemplate property.

gehho
Wow, concise! thanks mate, just what i was after!
TerrorAustralis
Just a followup question. I checked out the MSDN site and a few child links off it, i just need to know one thing about the TargetType or DataType property... If i have a seperate C# project that has a class in it, can i use that class as the type? for instance, project1 has the datatemplate in it, Project2 has a class with the ID, Name and Description. if i use TargetType="{x:Type Project2:DataClass}" will that work? (assuming i have defined a namespace for Project2
TerrorAustralis
Yes, this should work. Of course, you need to add Project2 as a reference in Project1, so that the type is known. Otherwise, you would not be able to create the appropriate namespace. Just try it out, it should work. BTW: I just updated my answer to use `DataType` instead of `TargetType`. Wrote that XAML completely from memory, but I think you already found that little bug. :)
gehho