我正在使用WPF,我有DataTemplate,我想访问代码隐藏我如何使用它?

时间:2017-01-25 09:22:03

标签: c# wpf xaml datatemplate code-behind

我正在使用WPF并且我有DataTemplate,我想访问代码隐藏我如何使用它?

<DataTemplate x:Name="PersonDateTemplate">
    <StackPanel Orientation="Horizontal">
         <Label x:Name="lblhr" Height="40px" Width="50px"
                Content="{Binding Path=hrvalueinitially}" FontSize="20px"
                HorizontalAlignment="Left" Background="#555555" Foreground="White"
                FlowDirection="LeftToRight"></Label>
         <TextBlock x:Name="items" Text="{Binding}" Margin="35,0,0,0"></TextBlock>
     </StackPanel>
</DataTemplate>

2 个答案:

答案 0 :(得分:0)

如果您在资源中使用DataTemplate并且已定义Key,则可以按如下方式访问CodeBehind中的资源,

-

或者如果您想在CodeBehind中从头开始创建,则应使用FrameworkElementFactory

答案 1 :(得分:0)

您可以使用dataTemplate替换ListBox,ComboBox或ListView等控件中数据项的可视外观。 要了解如何使用dataTemplate,我已经完成了以下示例:

    <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding ID}" FontSize="24"/>
                    <TextBlock Text=". Name: " FontSize="24"/>
                    <TextBlock Text="{Binding Name}" FontSize="24"/>
                    <TextBlock Text=" ,Age: " FontSize="24"/>
                    <TextBlock Text="{Binding Age}" FontSize="24"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

为了更好地了解数据模板,您可以点击以下链接: https://msdn.microsoft.com/en-us/library/ms742521(v=vs.110).aspx