2013-03-08 47 views
2

這很奇怪。以下代碼的要點是支持附加屬性,該附加屬性將通知容器是否有任何兒童已獲得焦點。LogicalTreeHelper.GetChildren - ObservableCollection Move()導致DataTemplate中的ContentControl失去其內容?

即我有一個網格,一個TextBox某處它的內容,我想轉網格藍如果這些控件之一獲得焦點。

我有一個ListView與ItemsTemplate。 ItemsTemplate是一個包含一些東西的DataTemplate ......但其中一個是ContentControl。

實施例:

<ListView> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
     <Grid> 
      <Border> 
      <ContentControl Content="{Binding Something}"/> 
      </Border> 
     </Grid> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
</ListView> 

在ContentControl中的結合應顯示特定類型的用戶控件的。 創建時...工作得很好。如果我遞歸迭代從Grid元素開始的listViewItem的模板,它也會遍歷ContentControl的「Content」。

但是,一旦我在ListView ItemsSource綁定的ObservableCollection上執行.Move(),根據LogicalTreeHelper,ContentControl.Content爲空。

什麼給?

如果我檢查ContentControl中,它讓我看到的內容...但LogicalTreeHelper.GetChildren返回空枚舉。

我很困惑...

任何人都可以解釋爲什麼會出現這種情況?

LogicalTreeHelper iterator方法

public static void applyFocusNotificationToChildren(DependencyObject parent) 
{ 
    var children = LogicalTreeHelper.GetChildren(parent); 

    foreach (var child in children) 
    { 
    var frameworkElement = child as FrameworkElement; 

    if (frameworkElement == null) 
     continue; 

    Type frameworkType = frameworkElement.GetType(); 

    if (frameworkType == typeof(TextBox) || frameworkType == typeof(ListView) || 
     frameworkType == typeof(ListBox) || frameworkType == typeof(ItemsControl) || 
     frameworkType == typeof(ComboBox) || frameworkType == typeof(CheckBox)) 
    { 
     frameworkElement.GotFocus -= frameworkElement_GotFocus; 
     frameworkElement.GotFocus += frameworkElement_GotFocus; 

     frameworkElement.LostFocus -= frameworkElement_LostFocus; 
     frameworkElement.LostFocus += frameworkElement_LostFocus; 

     // If the child's name is set for search 
    } 

    applyFocusNotificationToChildren(child as DependencyObject); 
    } 
} 

回答

0

阿羅哈,

這裏是一個suggetion你如何能解決你的問題:

我不知道如果我正確的拼寫GotFocus事件,但它是一個RoutedEvent你可以在視覺樹中的任何地方使用它。

如果你的項目的一個接收聚焦,將的ListView得到通知和處理程序中,你可以做任何你想要的。

如何:

<ListView GotFocus="OnGotFocus"> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
     <Grid> 
      <Border> 
      <ContentControl Content="{Binding Something}"/> 
      </Border> 
     </Grid> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
</ListView> 

這只是證明你能夠做什麼一些隨機邏輯。

public void OnGotFocus(object sender, RoutedEventArgs e) 
{ 
    TreeViewItem item = sender as TreeViewItem; 

    if(((MyViewModel)item.Content).SomeColor == "Blue") 
    { 
    Grid g = VisualTreeHelper.GetChild(item, 0) as Grid; 
    g.Background = Colors.Blue; 
    } 
} 

GotFocus是一個RoutedEvent,如果被觸發,它會冒泡視覺樹。所以趕上事件的地方,並檢查哪個是最初的源對象,引發了事件。或者檢查發射該事件的對象的ViewModel屬性是什麼。