0

I am searching a control using LogicalTreeHelper.FindLogicalNode in a RibbonWindow. The element I am searching yields the error: Specified method is not supported. If the Ribbon control is removed from XAML or if it is moved behind the TextBlock FindLogicalNode works fine. Has anyone an explanation?

Here's the 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>

Here's the code behind:

public partial class MainWindow : RibbonWindow
{
    public MainWindow()
    {
        InitializeComponent();
        TextBox textBox = (TextBox)System.Windows.LogicalTreeHelper.FindLogicalNode(this, "myTextBox");
    }
}
Johannes Schacht
  • 930
  • 1
  • 11
  • 28

1 Answers1

0

You could use the a helper method that finds the TextBox in the visual tree once it has been loaded:

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;
                }
            }
        }
    }
}
Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88