0

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>
Vijay
  • 663
  • 4
  • 15
user688
  • 361
  • 3
  • 22

2 Answers2

0

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

Community
  • 1
  • 1
WPFUser
  • 1,145
  • 7
  • 24
0

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

Tasnim Fabiha
  • 1,148
  • 1
  • 17
  • 31