查找DataTemplate生成的元素

本文关键字:元素 DataTemplate 查找 | 更新日期: 2023-09-27 18:19:29

我正在将列表框的TextBlock元素的IsEnabled属性更改为

    <ListBox Name="myListBox" ItemTemplate="{StaticResource myDataTemplate}"
     IsSynchronizedWithCurrentItem="True">
      <ListBox.ItemsSource>
      <Binding Source="{StaticResource InventoryData}" XPath="Books/Book"/>
      </ListBox.ItemsSource>
   </ListBox>

ListBox使用以下DataTemplate作为

   <DataTemplate x:Key="myDataTemplate">
      <TextBlock Name="textBlock" FontSize="14" Foreground="Blue">
      <TextBlock.Text>
     <Binding XPath="Title"/>
     </TextBlock.Text>
     </TextBlock>
   </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
   myTextBlock.IsEnabled=false;

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


但是如何为该列表框中的所有文本块设置isEnabled = false;

查找DataTemplate生成的元素

不要那样做。如果存在虚拟化,某些项目的容器甚至不会存在,您将需要处理相当混乱的代码来解决这个问题。请尝试绑定IsEnabled,并相应地设置属性/XML属性。

只需使用foreach循环迭代列表框中的所有项目,并执行与您已经对一个项目执行的操作相同的操作

foreach (ListBoxItem item in yourListBox.Items)
        {
        // Getting the ContentPresenter of myListBoxItem
        ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(item );    
        // 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
        myTextBlock.IsEnabled=false;
        }

但是

这不是推荐的方法。相反,您应该为此目的使用绑定

在您的items sourcebind中创建一个bool类型的属性textbox IsEnabled property。当您想要disable/enable时,文本框只需更改bool属性,textbox将根据布尔值自动为enabled or disabled

 <TextBlock Name="textBlock" IsEnabled="{Binding path=SomeBoolProperty"} FontSize="14" Foreground="Blue">