• 寻找到DataTemplate中定义的元素


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

    在ListBoxItem中应用它:

    <ListBox Name="myListBox" ItemTemplate="{StaticResource myDataTemplate}"
             IsSynchronizedWithCurrentItem="True">
      <ListBox.ItemsSource>
        <Binding Source="{StaticResource InventoryData}" XPath="Books/Book"/>
      </ListBox.ItemsSource>
    </ListBox>
    这里IsSynchronizedWithCurrentItem="True"保证SelectedItem就是CurrentItem。
    如果要找到DataTemplate为具体的某一个ListBoxItem生成的TextBlock元素,就先要找到这个ListBoxItem里面的ContentPresenter,然后调用DataTemplate的FindName方法:
    // Getting the currently selected ListBoxItem
    // Note that the ListBox must have
    // IsSynchronizedWithCurrentItem set to True for this to work
    ListBoxItem myListBoxItem =
        (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));

    // Getting the ContentPresenter of myListBoxItem
    ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);

    // Finding textBlock from the DataTemplate that is set on that ContentPresenter
    DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
    TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);

    // Do something to the DataTemplate-generated TextBlock
    MessageBox.Show("The text of the TextBlock of the selected list item: "
        + myTextBlock.Text);

    下面这个where型的写法用来寻找obj里面的一个类型为childItem的child,在本例中就是寻找myListBoxItem里面的一个类型为ContentPresenter的child。
    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;
    }

  • 相关阅读:
    《.NET分布式应用程序开》读书笔记 第一章:理解分布式架构
    一个DataSet的工具类,可以将DataTime的Time部分去掉,主要在序列化Xml时有用.
    Microsoft SQL Server 2005技术内幕系列书籍
    COM+客户端部署发现
    PowerDesigner中三种模型的转换关系图
    将ASP.NET页面内容输出到字符串中
    在WinForms中隐藏Crystal Report的[MainReport]标签页
    qmake常用语法一
    MinGW简介
    Qt的prx文件
  • 原文地址:https://www.cnblogs.com/bear831204/p/1313432.html
Copyright © 2020-2023  润新知