3

I have created class that inherits from Window and I am applying control template to it:

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

3 Answers 3

1

Using FindName in OnApplyTemplate is the correct way of doing it; I think it doesn't work because you forgot to call base.OnApplyTemplate().

Sign up to request clarification or add additional context in comments.

2 Comments

I tried it already, doesn't work, although it should, at least in theory.
Yes, but not today, I am home now, I will post it as soon as I get to work tomorrow.
0

My bet is that you are looking for a command that doesn't exist (or has a different name) or isn't a RibbonCommand.

That or you didn't specify x:FieldModifier="protected" for the command in xaml.

1 Comment

No, because it works in extended class, as I stated in the question.
0

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. 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.