2017-03-06 1 views
0

Je recherche un contrôle en utilisant LogicalTreeHelper.FindLogicalNode dans un RibbonWindow. L'élément que je recherche génère l'erreur: La méthode spécifiée n'est pas prise en charge. Si le contrôle Ribbon est supprimé de XAML ou s'il est déplacé derrière le TextBlockFindLogicalNode fonctionne correctement. Quelqu'un at-il une explication?FindLogicalNode échoue lors de la recherche dans RibbonWindow

Voici le XAML:

<RibbonWindow x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:local="clr-namespace:WpfApplication1" 
    mc:Ignorable="d" 
    Title="MainWindow" Height="350" Width="525"> 

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto"/> 
     <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 

    <Ribbon Grid.Row="0"/> <!-- if moved behind the TextBox or removed it works --> 
    <TextBox Name="myTextBox" /> 
</Grid> 

Voici le code derrière:

public partial class MainWindow : RibbonWindow 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     TextBox textBox = (TextBox)System.Windows.LogicalTreeHelper.FindLogicalNode(this, "myTextBox"); 
    } 
} 

Répondre

0

Vous pouvez utiliser la méthode d'aide qui trouve le TextBox dans l'arbre visuel une fois a été chargé:

Find all controls in WPF Window by type

public partial class MainWindow : RibbonWindow 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     this.Loaded += (s, e) => 
     { 
      TextBox textBox = FindVisualChildren<TextBox>(this).FirstOrDefault(x => x.Name == "myTextBox"); 
     }; 
    } 

    private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject 
    { 
     if (depObj != null) 
     { 
      for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) 
      { 
       DependencyObject child = VisualTreeHelper.GetChild(depObj, i); 
       if (child != null && child is T) 
       { 
        yield return (T)child; 
       } 

       foreach (T childOfChild in FindVisualChildren<T>(child)) 
       { 
        yield return childOfChild; 
       } 
      } 
     } 
    } 
} 
+0

Merci pour la solution. Avez-vous une idée pourquoi FindLogicalNode échoue? –

+0

Parce que le TextBox est introuvable dans l'arborescence * logical *. – mm8