How can I find WPF controls by name or type?

后端 未结 18 2994
庸人自扰
庸人自扰 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:44

    You can also find an element by name using FrameworkElement.FindName(string).

    Given:

    
        
    
    

    In the code-behind file, you could write:

    var myTextBlock = (TextBlock)this.FindName("myTextBlock");
    

    Of course, because it's defined using x:Name, you could just reference the generated field, but perhaps you want to look it up dynamically rather than statically.

    This approach is also available for templates, in which the named item appears multiple times (once per usage of the template).

提交回复
热议问题