我创建了一个继承自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;
}
我想在控件模板中找到一些控件:
public override void OnApplyTemplate() {
RibbonCommand searchCommand = this.Template.FindName("searchCommand", this) as RibbonCommand;
//doesn't work, searchCommand is null
searchCommand.CanExecute += CanExecuteRibbonCommand;
}
但它始终是null。我在继承类中尝试过,它可以工作,但我想在我的基类中使用它,这样我就不必每次使用该类时都要搜索它。这样可以解决问题:
public partial class MainWindow : BaseSearchWindow {
public MainWindow() {
InitializeComponent();
RibbonCommand searchCommand = this.Template.FindName("searchCommand", this) as RibbonCommand;
searchCommand.CanExecute += CanExecuteRibbonCommand;
}