In XAML, I have:
<DataTemplate x:Key="AgeItemTemplate">
<Border BorderThickness="0,0,0,0" BorderBrush="#6FBDE8">
<TextBlock Margin="2" Text="{Binding Age}" VerticalAlignment="Center" Grid.Column="1" />
</Border>
</DataTemplate>
How could I use that DataTemplate in code?
I know I can create a new template and linked to a gridview column but I want to define that template in xaml. Is there any way to开发者_C百科 modify and use that dataTemplate in code behind?
You need to use the findresource method on FrameworkElement.
<DataTemplate x:Key="PersonItemTemplate" x:Name="someTemplate">
<Border BorderThickness="0,0,0,0" BorderBrush="#6FBDE8">
<Grid Margin="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="32" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Image Source="Images/person.png" Width="24" Height="24" Grid.Column="0" HorizontalAlignment="Center" />
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" Grid.Column="1" />
</Grid>
</Border>
</DataTemplate>
code behind:
template1 = (DataTemplate)FindName("someTemplate");
linkColumn1 = new GridViewColumn
{
Header = "Test",
CellTemplate = template1,
//Width = 88, // Comment out to set to auto
};
gv.Columns.Add(linkColumn1);
as a result I was able to duplicate a column with code:
this is helpful to populate a listview dynamically because it is harder to create the styles on code I believe.
精彩评论