开发者

Finding controls in WPF ControlTemplate

开发者 https://www.devze.com 2023-02-22 14:48 出处:网络
I have created class that inherits from Window and I am applying control 开发者_如何学Pythontemplate to it:

I have created class that inherits from Window and I am applying control 开发者_如何学Pythontemplate 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;

        }   


Using FindName in OnApplyTemplate is the correct way of doing it; I think it doesn't work because you forgot to call 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.

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消