Vale
Vale

Reputation: 3298

Finding controls in WPF ControlTemplate

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;

        }   

Upvotes: 3

Views: 3256

Answers (3)

Vale
Vale

Reputation: 3298

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.

Upvotes: 0

Emond
Emond

Reputation: 50672

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.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292345

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

Upvotes: 1

Related Questions