Datatemplate without Listbox/Itemssource

青春壹個敷衍的年華 提交于 2019-12-11 09:13:45

问题


I'm fairly new to WPF, and I'm having a difficulty understanding the subtlety of DataTemplate, DataContext and ofcourse - MVVM. My problem is this: I want to create a DataTemplate for the class Person - which contains a grid which contains three lables - for the First Name, Last Name and Age. After creating my DataTemplate, I wish to add a person to the main grid in the mainwindow, without a listbox or a component which has ItemSource.

To sum up my question - I want to know if there's a way to visualize objects with DataTemplate in which i dont have to add them to a collection and then to ItemsSource.

Thanks!


回答1:


What you need is a ContentPresenter, this element displays the data specified by its Content property using the DataTemplate specified by its ContentTemplate property. So, in your example, you can use the following:

<ContentPresenter ContentTemplate={StaticResource YourTemplate}
                  Content={Binding PathToYourPerson}/>

For reference, this is the element that controls such as Buttons use within their template to render their content.



来源:https://stackoverflow.com/questions/4787500/datatemplate-without-listbox-itemssource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!