开发者

How to create a template to display data from a class in WPF

开发者 https://www.devze.com 2022-12-27 03:12 出处:网络
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.Des

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 con开发者_JAVA百科trol 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 :)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消