Reputation: 61382
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)
Upvotes: 1
Views: 144
Reputation: 184376
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
}
Upvotes: 2