开发者

How to edit/use xaml datatemplate in code

开发者 https://www.devze.com 2023-03-15 10:03 出处:网络
In XAML, I have: <DataTemplate x:Key=\"AgeItemTemplate\"> <Border BorderThickness=\"0,0,0,0\" BorderBrush=\"#6FBDE8\">

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?

How to edit/use xaml 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:

How to edit/use xaml datatemplate in code

this is helpful to populate a listview dynamically because it is harder to create the styles on code I believe.

0

精彩评论

暂无评论...
验证码 换一张
取 消