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.
我有一个带有DataTemplate的ItemsControl,用于描述如何显示每个项目。我想在DataTemplate中使用的UI不适合用XAML建模,我将不得不在代码中填充Grid。
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?
每次我的DataTemplate实例化时如何运行此代码,以便我有机会填充我在XAML中无法表达的位?
To expand a little, consider a simplified example. The VM looks like this:
为了扩展一点,请考虑一个简化的例子。 VM看起来像这样:
class MyItem
{
public string Name { get; set; }
public MyGrid Grid { get; set; } // describes a complex grid-like model
}
The DataTemplate
looks like this:
DataTemplate看起来像这样:
<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?
我想在基于MyItem.Grid的代码中填充
(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 个解决方案
#1
2
You can easily hook the Loaded
event on the Grid
.
您可以轻松地在网格上挂载Loaded事件。
<Grid Loaded="Grid_Loaded">
private void Grid_Loaded(object sender, ....)
{
var grid = (Grid)sender;
var item = (MyItem)grid.DataContext;
//Go time
}
#1
2
You can easily hook the Loaded
event on the Grid
.
您可以轻松地在网格上挂载Loaded事件。
<Grid Loaded="Grid_Loaded">
private void Grid_Loaded(object sender, ....)
{
var grid = (Grid)sender;
var item = (MyItem)grid.DataContext;
//Go time
}