How to populate a control inside a DataTemplate whenever the template is instantiated?

烈酒焚心 提交于 2019-12-11 07:17:45

问题


I have an ItemsControl with a DataTemplate describing how to display each item. The UI I'd like to have inside the DataTemplate is a bad fit to be modelled by XAML and I am going to have to populate a Grid in code.

How do I get this code to run every time my DataTemplate is instantiated, so that I get a chance to populate the bits I couldn't express in XAML?


To expand a little, consider a simplified example. The VM looks like this:

class MyItem
{
    public string Name { get; set; }
    public MyGrid Grid { get; set; } // describes a complex grid-like model
}

The DataTemplate looks like this:

<DataTemplate>
    <TextBlock Text="{Binding Name}"/>
    <Grid/>
</DataTemplate>

The <Grid/> is the thing I want to populate in code based on MyItem.Grid. How can I do this?

(If you are going to say that I shouldn't populate the <Grid/> in code but just use XAML, please answer this question instead)


回答1:


You can easily hook the Loaded event on the Grid.

<Grid Loaded="Grid_Loaded">
private void Grid_Loaded(object sender, ....)
{
    var grid = (Grid)sender;
    var item = (MyItem)grid.DataContext;
    //Go time
}


来源:https://stackoverflow.com/questions/12121580/how-to-populate-a-control-inside-a-datatemplate-whenever-the-template-is-instant

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