简体   繁体   中英

I am using WPF and I have DataTemplate that is i want to access into the codebehind how I can use this?

I am using WPF and I have DataTemplate that is i want to access into the codebehind how I can use this?

<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>

If you are having the DataTemplate in Resource and you have Key defined, you can access the resource in CodeBehind as follows,

DataTemplate dataTemplate = App.Current.TryFindResource("PersonDateTemplate") as DataTemplate;

or if you want create from scratch in CodeBehind, you should use FrameworkElementFactory

You can use dataTemplate to replace the visual appearance of a data item in a control like ListBox, ComboBox or ListView. To understand how to work with dataTemplate I've done the following example:

    <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>

For better understanding about the data template you may follow the following link: https://msdn.microsoft.com/en-us/library/ms742521(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM