views:

33

answers:

2

Hi,

I have a TabControl

 <TabControl 
    Name="myTabControl"
        IsSynchronizedWithCurrentItem="True" 
        ItemsSource="{Binding}">                            
               <TabControl.ItemTemplate>
                   <DataTemplate>
                           <DockPanel Width="120">
                                <Button Name="CloseScreen"/>
                                <ContentPresenter Content="{Binding Path=DisplayName}"/>
                          </DockPanel>
                   </DataTemplate>
               </TabControl.ItemTemplate>
 </TabControl>

I want to find the button which is located in the ItemTemplate from code.

Thank you.

A: 

If your intention is using the click event, try using a command instead.

Sdry
No, I want to find the button instance at runtime.
frameworkninja
+1  A: 

You could try LogicalTreeHelper.FindLogicalNode. For example:

var button = LogicalTreeHelper.FindLogicalNode(myTabControl, "CloseScreen");

But beware: because you're using a DataTemplate for your tab items, you'll end up with multiple buttons called CloseScreen, and FindLogicalNode will probably only return the first.

Another approach is to search the logical tree recursively using LogicalTreeHelper.GetChildren. The problem you might face here is knowing when to stop.

Samuel Jack
yeah it works ;) thank you.
frameworkninja