OnApplyTemplate 未在自定义控件中调用 [英] OnApplyTemplate not called in Custom Control
问题描述
我有一个自定义控件,它使用了一些 PART 控件:
I have a Custom Control which uses some PART controls:
[TemplatePart(Name = "PART_TitleTextBox", Type = typeof(TextBox))]
[TemplatePart(Name = "PART_TitleIndexText", Type = typeof(Label))]
[TemplatePart(Name = "PART_TimeCodeInText", Type = typeof(TextBlock))]
[TemplatePart(Name = "PART_TimeCodeOutText", Type = typeof(TextBlock))]
[TemplatePart(Name = "PART_ApprovedImage", Type = typeof(Image))]
[TemplatePart(Name = "PART_CommentsImage", Type = typeof(Image))]
[TemplatePart(Name = "PART_BookmarkedImage", Type = typeof(Image))]
public class TitleBoxNew : Control
{
static TitleBoxNew()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(TitleBoxNew),
new FrameworkPropertyMetadata(typeof(TitleBoxNew)));
}
public TitleBoxNew() { }
// ... rest of class
}
此控件覆盖 OnApplyTemplate:
This control is overriding OnApplyTemplate:
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
InitializeEvents();
}
大多数情况下效果很好.我在窗口中的自定义选项卡控件中添加了控件,并且以某种方式从未为该控件调用 OnApplyTemplate !为什么这不像我期望的那样工作?
Which works well, most of the time. I have added the control inside a custom tab control in a window and somehow OnApplyTemplate is never called for that control! Why doesn't this work as I expect?
推荐答案
对于可能偶然发现这篇文章的其他人,我遇到了同样的问题,我设法通过将以下内容添加到包含我的自定义控件的项目:
For anyone else who might stumble upon this post, I was having the same issue and I managed to solve it by adding the following into the AssemblyInfo.cs of the project containing my custom control:
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
我的控件模板位于与控件相同的项目中的 Theme/Generic.xaml 文件中.
My control's template is located in the file Theme/Generic.xaml in the same project as the control.
这篇关于OnApplyTemplate 未在自定义控件中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!