How can I find WPF controls by name or type?

后端 未结 18 3001
庸人自扰
庸人自扰 2020-11-21 04:23

I need to search a WPF control hierarchy for controls that match a given name or type. How can I do this?

18条回答
  •  失恋的感觉
    2020-11-21 04:49

    Since the question is general enough that it might attract people looking for answers to very trivial cases: if you just want a child rather than a descendant, you can use Linq:

    private void ItemsControlItem_Loaded(object sender, RoutedEventArgs e)
    {
        if (SomeCondition())
        {
            var children = (sender as Panel).Children;
            var child = (from Control child in children
                     where child.Name == "NameTextBox"
                     select child).First();
            child.Focus();
        }
    }
    

    or of course the obvious for loop iterating over Children.

提交回复
热议问题