开发者

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

I have a TabControl

 <TabControl 
    Name="myTabControl"
        IsSy开发者_Go百科nchronizedWithCurrentItem="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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜