在RibbonWindow中搜索时,FindLogicalNode失败

时间:2017-03-06 10:21:44

标签: wpf wpf-controls

我在LogicalTreeHelper.FindLogicalNode中使用RibbonWindow搜索控件。我正在搜索的元素产生错误:不支持指定的方法。如果从XAML移除了Ribbon控件,或者移动了TextBlock FindLogicalNode后面的<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> 控件正常工作。有没有人解释?

这是XAML:

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

这是背后的代码:

value = Max_Date[0]
new_val= datetime.datetime.strptime( str( value ), '%Y%m%d').strftime('%m/%d/%y')

1 个答案:

答案 0 :(得分:0)

您可以使用一个辅助方法,一旦加载,就会在 visual 树中找到TextBox

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