查找DataTemplate生成的元素

时间:2012-01-03 08:46:08

标签: c# wpf

我正在改变列表框的TextBlock元素的IsEnabled prop,如下所示

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


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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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

<强> BUT

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

在您的boolitems source bind textbox中创建IsEnabled property类型的媒体资源。当您想要disable/enable文本框时,只需更改bool属性,textbox将根据bool值自动enabled or disabled

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