我有一个自定义控件包含在WPF自定义控件库中,其中OnApplyTemplate()方法仅在我在Visual Studio 2012中运行调试器时每隔一次调用。更具体地说,我设置了一个断点在OnApplyTemplate()方法中,第一次运行调试器时,它永远不会被调用(并且我在方法中放入的代码没有被执行),但是当我选择“重新启动”时,它每次都被调用。
我已经查看了类似性质的二十几个问题/答案,所有建议确保在静态构造函数(已完成)中设置DefaultStyleKeyProperty,并在AssemblyInfo.cs文件中设置ResourceDictionaryLocation.None和ResourceDictionaryLocation.SourceAssembly (已完成)。
我已经制作了数十个自定义控件而没有出现此问题。这是基本结构:
[TemplatePart(Name = "PART_FileTree", Type = typeof(CustomTreeView))]
public class ExplorerComboBox: Control, INotifyPropertyChanged {
static ExplorerComboBox () {
DefaultStyleKeyProperty.OverrideMetadata(typeof(blinzExplorerComboBox), new FrameworkPropertyMetadata(typeof(blinzExplorerComboBox)));
}
public override void OnApplyTemplate () {
base.OnApplyTemplate();
_fileTree = (CustomTreeView)Template.FindName("PART_FileTree", this);
if (_fileTree != null) {
_fileTree.SelectedItemChanged += part_fileTree_SelectedItemChanged;
_fileTree.SelectionMode = SelectionModalities.SingleSelectionOnly;
try {
var drives = DriveInfo.GetDrives();
foreach (var drive in drives) {
_fileTree.Items.Add(new FileSystemObjectInfo(drive));
}
} catch {
throw new NotImplementedException();
}
} else {
throw new NotImplementedException();
}
}//OnApplyTemplate
}
奇怪的是,当没有调用OnApplyTemplate时,子CustomTreeView仍会填充文件信息,但永远不会设置事件处理程序'SelectedItemChanged'。