zoukankan      html  css  js  c++  java
  • 寻找到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;
    }

  • 相关阅读:
    Spring 控制反转容器(Inversion of Control – IOC)
    理解依赖注入(DI
    创建一个简单的Spring应用
    Spring开发环境搭建(Eclipse)
    Spring框架模块
    Spring 框架介绍
    spring教程
    Bulma CSS
    Bulma CSS
    Bulma CSS
  • 原文地址:https://www.cnblogs.com/bear831204/p/1313432.html
Copyright © 2011-2022 走看看