简体   繁体   English

在WPF ControlTemplate中查找控件

[英]Finding controls in WPF ControlTemplate

I have created class that inherits from Window and I am applying control template to it: 我创建了继承自Window的类,我将控制模板应用于它:

public class BaseSearchWindow : Window {
        static BaseSearchWindow() {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(BaseSearchWindow), new FrameworkPropertyMetadata(typeof(BaseSearchWindow)));
        }
        public BaseSearchWindow() {
            Uri uri = new Uri("/WPFLibs;component/Resources/StyleResources.xaml", UriKind.Relative);
            ResourceDictionary Dict = Application.LoadComponent(uri) as ResourceDictionary;
            this.Style = Dict["WindowTemplate"] as Style;
        }

Than I want to find some control in control template: 比我想在控制模板中找到一些控件:

 public override void OnApplyTemplate() {

                RibbonCommand searchCommand = this.Template.FindName("searchCommand", this) as RibbonCommand;
               //doesn't work, searchCommand is null
                searchCommand.CanExecute += CanExecuteRibbonCommand;
    }

But it is allways null. 但总是空的。 I tried it in inherited class and it works, but I want it in my base class, so I don't have to search for it every time I use that class. 我在继承的类中尝试了它并且它可以工作,但是我希望它在我的基类中,所以我不必每次使用该类时都搜索它。 This works: 这有效:

public partial class MainWindow : BaseSearchWindow {
        public MainWindow() {
            InitializeComponent();
            RibbonCommand searchCommand = this.Template.FindName("searchCommand", this) as RibbonCommand;
            searchCommand.CanExecute += CanExecuteRibbonCommand;

        }   

Using FindName in OnApplyTemplate is the correct way of doing it; OnApplyTemplate使用FindName是正确的方法; I think it doesn't work because you forgot to call base.OnApplyTemplate() . 我认为它不起作用,因为你忘了调用base.OnApplyTemplate()

My bet is that you are looking for a command that doesn't exist (or has a different name) or isn't a RibbonCommand. 我敢打赌,您正在寻找一个不存在(或具有不同名称)或不是RibbonCommand的命令。

That or you didn't specify x:FieldModifier="protected" for the command in xaml. 那个或者你没有为xaml中的命令指定x:FieldModifier="protected"

Actually, I made a mistake. 实际上,我犯了一个错误。 When I try to find controls that are not RibbonCommands it worked, so now I find parent control first and than use VisualTreeHelper to find the RibbonCommand. 当我尝试找到不是RibbonCommands的控件时,它现在可以找到父控件,而不是使用VisualTreeHelper来查找RibbonCommand。 Sorry about that, I was convinced that it worked only in extended class, but I guess I was too tired when I posted the question. 对此我很抱歉,我确信它只适用于扩展课程,但我想在发布问题时我太累了。 Thank you for your help anyway. 无论如何,谢谢你的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM