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;
    }

  • 相关阅读:
    小程序导出excel
    小程序搜索框加icon
    微信小程序全局传参 app传参
    长亭安服面经
    uni关于生成支付宝小程序问题
    Echarts图表使用
    js获取url路径斜杠分开
    git---更新gitignore文件,使之生效
    常见Cpu 100%的原因
    OFFICE 2019 INSTRUCTIONS
  • 原文地址:https://www.cnblogs.com/bear831204/p/1313432.html
Copyright © 2011-2022 走看看