Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have below situation

Have a DataTemplate like below
XML
<DataTemplate x:Key="editableName">
    <TextBox x:Name="hTreeRenameBox" />
</DataTemplate>


Have a treeview like below
XML
<TreeView x:Name="hScExTrview" BorderBrush="Brown" Background="#FF1E1E1E" BorderThickness="1" Margin="0,-1,-1,0" ToolTip="Session Scripts">
</TreeView>


Now I have created some TreeItems for the treeview from Code.

One point I have selected one context menu which is part of the treeview and I have the below code to add the DataTemplate with TreeView Item like below

TreeViewItem pp = (TreeViewItem)hScExTrview.SelectedItem;
String kk = (String)pp.Header;
pp.HeaderTemplate = (DataTemplate)this.Resources["editableName"];


Now my query is I want to get "hTreeRenameBox" which is declared inside DataTemplate. How I can get that from the above C# code.

I used the below code but it is not working; kindly correct me!
TextBox textBoxAnswer = pp.HeaderTemplate.FindName("hTreeRenameBox",pp) as TextBox;
Posted
Comments
johannesnestler 30-Apr-15 8:39am    
did you solve it?

1 solution

Hi Toufique.

You could use FrameworkTemplate's Find method to get a named element from a template.

In your case you have a "Problem" because the Header is in the default TreeViewItem ControlTemplate represented by a ContentPresenter like this:

XML
<ContentPresenter x:Name="PART_Header" ContentSource="Header" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>


So the solution could work like this:

C#
// Get the HeaderTemplate used by the TreeViewItem
FrameworkTemplate ft = pp.HeaderTemplate;
// Get the FrameworkElement your Template is applied to - it's the ContentPresenter from your TreeViewItem Template (if you haven't overriden it..)
ContentPresenter presenterHeader = pp.Template.FindName("PART_Header", pp) as ContentPresenter;
// Now we can find the elements of the Template from the FrameworkElement it was applied to (the ContentPresenter)
TextBox obj = ft.FindName("hTreeRenameBox", presenterHeader ) as TextBox;



Kind regards Johannes

P.S. maybe try a proper MVVM pattern implementation with your WPF Project, and get rid of your code-behind and such "problems"?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900