2012-01-03 77 views
0

餘米改變列表框的TextBlock元素的IsEnabled道具如下查找的DataTemplate生成的元素

<ListBox Name="myListBox" ItemTemplate="{StaticResource myDataTemplate}" 
    IsSynchronizedWithCurrentItem="True"> 
     <ListBox.ItemsSource> 
     <Binding Source="{StaticResource InventoryData}" XPath="Books/Book"/> 
     </ListBox.ItemsSource> 
    </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; 
    } 


但我如何爲所有Te設置isEnabled = false;該列表框中的xtBlocks?

回答

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

這不是推薦的方法來做這個。相反,你應該使用綁定爲此

items sourcebindtextboxIsEnabled property用它創建一個bool類型屬性。當你想disable/enable文本框簡單地改變bool財產和textbox將基於布爾值

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

不要做自動enabled or disabled。如果有虛擬化,某些項目的容器甚至不會存在,您需要處理相當混亂的代碼來解決該問題。嘗試綁定IsEnabled,並相應地設置屬性/ XML屬性。

+0

是的,這是正確的感謝 – 2012-01-03 09:35:42