如何从tabitem wpf的数据模板中找到控件 [英] How to find control from datatemplate of tabitem wpf

查看:55
本文介绍了如何从tabitem wpf的数据模板中找到控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 TabControl:

I have TabControl:

<TabControl Name="tabControl"                   
            VerticalAlignment="Top"
            HorizontalAlignment="Stretch">
    <TabControl.Items>
        <TabItem  x:Name="tab1" Header="ABC">                       
            <TabItem.ContentTemplate>                            
                <DataTemplate>
                    <ScrollViewer Name="ScrollViewer">
                        <StackPanel Orientation="Vertical">
                            <TextBox Name="txt1" HorizontalAlignment="Center" Margin="0,26,0,0" />
                            <ListBox Name="listBox" DataContext="{Binding Items, Mode=TwoWay}"  />
                        </StackPanel>
                    </ScrollViewer>
                </DataTemplate>
            </TabItem.ContentTemplate>
        </TabItem>
    </TabControl.Items>
</TabControl>

如何在 C# 代码中以编程方式获取列表框?

How I can get listbox programmatically in C# code?

我尝试了以下代码,myContentPresenter.ContentTemplate 显示为空.

I have tried below code and myContentPresenter.ContentTemplate shows null.

TabItem myListBoxItem = (TabItem)(tabControl.ItemContainerGenerator.ContainerFromItem(tabControl.SelectedItem));
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
ListBox listBox = (ListBox)myDataTemplate.FindName("listBox", myContentPresenter);

推荐答案

基于@mm8 方法,以下解决方案将按名称而不是按类型查找 ListBox:

Building on @mm8 approach, the following solution will find the ListBox by name instead of by type:

XAML

<TabControl x:Name="tabControl1" SelectionChanged="tabControl1_SelectionChanged">
    <TabItem  x:Name="tab1" Header="ABC">
        <TabItem.ContentTemplate>
            ...

代码

private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Dispatcher.BeginInvoke(new Action(() => TabItem_UpdateHandler()));
}


void TabItem_UpdateHandler()
{
    ContentPresenter myContentPresenter = tabControl1.Template.FindName("PART_SelectedContentHost", tabControl1) as ContentPresenter;
    if (myContentPresenter.ContentTemplate == tab1.ContentTemplate)
    {
        myContentPresenter.ApplyTemplate();
        var lb1 = myContentPresenter.ContentTemplate.FindName("listBox", myContentPresenter) as ListBox;
    }
}

这篇关于如何从tabitem wpf的数据模板中找到控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆