有一个Listbox,里面的Item是通过数据模板生成的,如下所示:

<Border Margin="15" BorderBrush="Aqua" BorderThickness="2" Padding="8" CornerRadius="5">
      <StackPanel>
        <ListBox Name="myListBox" ItemTemplate="{StaticResource myDataTemplate}"
                 IsSynchronizedWithCurrentItem="True">
          <ListBox.ItemsSource>
            <Binding Source="{StaticResource InventoryData}" XPath="Books/Book"/>
          </ListBox.ItemsSource>
        </ListBox>
        <Button Margin="10"
                Click="DataTemplateFindElement">Get text of textBlock in DataTemplate</Button>
      </StackPanel>
    </Border>

Listbox使用的数据模板如下:

<DataTemplate x:Key="myDataTemplate">
      <TextBlock Name="textBlock" FontSize="14">
        <TextBlock.Text>
          <Binding XPath="Title"/>
        </TextBlock.Text>
      </TextBlock>
    </DataTemplate>

使用下面的代码就可以获取数据模板里面TextBlock中的内容了。

ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;    
  TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);
MessageBox.Show("The text of the named TextBlock in the DataTemplate of the selected list item: " + myTextBlock.Text

上面代码调用的函数如下:

private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child != null && child is childItem)
                return (childItem)child;
            else
            {
                childItem childOfChild = FindVisualChild<childItem>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
        }
        return null;
    }

WPF中如何使用代码操作数据模板生成的控件的更多相关文章

  1. WPF中ContextMenu(右键菜单)使用Command在部分控件上默认为灰色的处理方法

    原文:WPF中ContextMenu(右键菜单)使用Command在部分控件上默认为灰色的处理方法 问题描述 今天发现如果我想在一个TextBlock弄一个右键菜单,并且使用Command绑定,结果发 ...

  2. WPF中获取Hwnd与窗体,Uid获取控件

    void MapControl_Loaded(object sender, RoutedEventArgs e) { this.OnApplyTemplate(); CurrentMapChanged ...

  3. eclipse中添加Java代码注释模板

    eclipse中添加Java代码注释模板 1.Window->Preference->Java->Code Style->Code Template,进入注释编辑界面 2.文件 ...

  4. arrays.xml中使用integer-array引用drawable图片资源,代码中如何将这些图片资源赋值到ImageView控件中

    当我们在arrays.xml文件中声明一些图片资源数组的时候: <?xml version="1.0" encoding="utf-8"?> < ...

  5. CStatic中保持图形比例不变,尽量填充控件空间的代码

    CStatic中保持图形比例不变,尽量填充控件空间的代码 先获取控件的高.宽,然后获取图像的高.宽,测试需要调整高还是调整宽 void CImagePreviewStatic::DrawItem(LP ...

  6. 《Programming WPF》翻译 第3章 3.内嵌控件

    原文:<Programming WPF>翻译 第3章 3.内嵌控件 WPF提供了一系列内嵌控件.其中大多数符合标准的你已经熟悉的Windows控件类型.注意到没有一个是包装在旧的Win32 ...

  7. 《Programming WPF》翻译 第3章 1.什么是控件

    原文:<Programming WPF>翻译 第3章 1.什么是控件 对于一个应用程序而言,控件是搭建用户界面的积木.它们具备交互式的特征,例如文本框.按钮以及列表框.尽管如此,WPF还有 ...

  8. WPF 模仿 UltraEdit 文件查看器系列一 用户控件

    WPF 模仿 UltraEdit 文件查看器系列一 用户控件 运行环境:Win10 x64, NetFrameWork 4.8, 作者:乌龙哈里,日期:2019-05-10 章节: 起步 添加用户控件 ...

  9. WPF通过不透明蒙板切割显示子控件

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/Backspace110/article/ ...

随机推荐

  1. pytorch将cpu训练好的模型参数load到gpu上,或者gpu->cpu上

    假设我们只保存了模型的参数(model.state_dict())到文件名为modelparameters.pth, model = Net() 1. cpu -> cpu或者gpu -> ...

  2. 线段树 Mayor's posters

    甚至DFS也能过吧 Mayor's posters POJ - 2528 The citizens of Bytetown, AB, could not stand that the candidat ...

  3. .NET重构(二):ArrayList,List,IList的联系和区别

    导读:在机房重构的时候,为了降低耦合,不能返回DataTable型数据,而需要转换为泛型集合.我一直使用的就是IList,那天师傅过来帮我挑错,问我:你为什么一直写IList呢,不应该是List吗?好 ...

  4. Replication and Triggers

    参考官网:https://dev.mysql.com/doc/refman/5.7/en/replication-features-triggers.html 需要了解复制和触发器关系的背景: 程序变 ...

  5. iOS学习笔记14-网络(三)WebView

    一.WebView WebView就是一个内嵌浏览器控件,在iOS中主要有两种WebView:UIWebView和WKWebView,UIWebView是iOS2之后开始使用,WKWebView是在i ...

  6. 《写给大忙人看的Java核心技术》 勘误

    先附上十分讨喜的封面.这应该是爱丽丝梦游仙境里的那只兔子吧? 勘误表基于原版勘误表制作 链接 截止日期 2017-02-09 对应<写给大忙人看的Java核心技术>2016年1月第1次印刷 ...

  7. java中执行JS脚本

    package 测试包; import javax.script.*; public class SSSSSSSSS { public SSSSSSSSS() { // TODO Auto-gener ...

  8. org.xml.sax.SAXParseException: 元素内容必须由格式正确的字符数据或标记组成,的错误问题

    当时在mapper其中的一个语句是case when ISNULL(b.c_truename) || LENGTH(TRIM(b.c_truename)) < 1 then b.c_ch_nam ...

  9. JS --- 数组循环要用length

    socket.on("receive", function (data) { deviceone.print("返回的数据:"+data) // 发送异常 va ...

  10. XP操作系统设置:[82]关机快捷键

    磨镰刀不少割麦,掌握了快速关机的多种方法,在尴尬的时候说不定还真能派上用场呢.   工具/原料   手提电脑.台式电脑.Windows 操作系统. 方法一:   1 Windows XP 操作系统中有 ...