mokaymakci
mokaymakci

Reputation: 1393

How can I find any control in the ItemTemplate of a TabControl?

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.

Upvotes: 1

Views: 1947

Answers (2)

Samuel Jack
Samuel Jack

Reputation: 33270

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.

Upvotes: 1

Samuel DR
Samuel DR

Reputation: 1231

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

Upvotes: 0

Related Questions