zoukankan      html  css  js  c++  java
  • 获得DateTemplate中的element

    比较困难的是用DataTemplate.FindName(string name,parent),需要知道这个datatemplate visual tree中的直系父亲,只要就是查找这个父亲了。

    例子:

    <DataTemplate x:Key="myDataTemplate">
      <TextBlock Name="textBlock" FontSize="14" Foreground="Blue">
        <TextBlock.Text>
          <Binding XPath="Title"/>
        </TextBlock.Text>
      </TextBlock>
    </DataTemplate>
    ItemsControl通过ItemContainerGenerator产生items, 从一个dataItem到visual tree item,能够用ItemContainerGenerator.ContainerFromIndex 或者 ItemContainerGenerator.ContainerFromItem获得一个 container,如一个TreeViewItem.相反还有ItemContainerGenerator.ContainerFromItem,ItemContainerGenerator.ItemFromContainer方法来从container获得index或者dataItem.

    重新转到获得dataTemplate, 例子:

    // 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);
    
    FindVisualChild方法:
    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;
    }
     参考:

    http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspxhttp://msdn.microsoft.com/en-us/library/bb613579.aspx

  • 相关阅读:
    quartz 中JobExecutionContext的使用
    Memcached 集群架构方面的问题
    Spring+Quartz 集群
    Spring Quartz 持久化解决方案
    不同版本(2.3,2.4,2.5) web.xml 的web-app头信息
    Spring Framework 4.0.0发布,首次支持Java 8
    Serializable java序列化
    Quartz 有状态的JobDataMap
    JobDataMap 不能被序列化如何解决研究中
    Spring-3.2.5 + Quartz-2.2.1 集群实例(Tomcat+Memcached+Quartz集群session共享)
  • 原文地址:https://www.cnblogs.com/liangouyang/p/1343937.html
Copyright © 2011-2022 走看看