我正在尝试制作一个基于文本框控件的自定义控件。此文本框控件还包含一个按钮、列表框和弹出窗口。我尝试在类的 OnApplyTemplate 函数中为按钮的鼠标按下事件添加一个事件处理程序。当我逐步调试时,会调用 OnApplyTemplate 并添加事件处理程序代码。
我的问题是,当我单击按钮时,不会调用事件处理程序子 DropDownButton_MouseDown。
这是我的课:
Imports System.Windows.Controls.Primitives
<TemplatePart(Name:="PART_ControlBorder", Type:=GetType(Border))> _
<TemplatePart(Name:="PART_DropDownButton", Type:=GetType(Button))> _
<TemplatePart(Name:="PART_Popup", Type:=GetType(Popup))> _
<TemplatePart(Name:="PART_ListBox", Type:=GetType(ListBox))> _
Public Class AutoCompleteTextBox
Inherits TextBox
#Region "DECLARATIONS"
Private Mainborder As Border
Private popup As Popup
Private listBox As ListBox
Private dropDownButton As Button
#End Region
#Region "METHODS"
Private Sub PopupOpen()
If popup IsNot Nothing And popup.IsOpen = False Then
popup.IsOpen = True
Else
Return
End If
End Sub
Private Sub DropDownButton_MouseDown(sender As Object, e As System.EventArgs)
PopupOpen()
End Sub
#End Region
#Region "APPLY TEMPLATE"
Public Overrides Sub OnApplyTemplate()
MyBase.OnApplyTemplate()
If Me.Template IsNot Nothing Then
Dim button__1 As Button = TryCast(Me.Template.FindName("PART_DropDownButton", Me), Button)
If button__1 IsNot dropDownButton Then
'First unhook existing handler
If dropDownButton IsNot Nothing Then
RemoveHandler dropDownButton.MouseDown, AddressOf DropDownButton_MouseDown
End If
dropDownButton = button__1
If dropDownButton IsNot Nothing Then
AddHandler dropDownButton.MouseDown, AddressOf DropDownButton_MouseDown
End If
End If
End If
End Sub
#End Region
#Region "CONSTRUCTOR"
Sub New()
DefaultStyleKeyProperty.OverrideMetadata(GetType(AutoCompleteTextBox), New FrameworkPropertyMetadata(GetType(AutoCompleteTextBox)))
End Sub
#End Region
End Class
我在 Visual Studio 2012 中使用 wpf .net 4.5。这是我的名为 AutoCompleteTextBox 的自定义控件的 xaml,该控件在解决方案中的另一个项目中定义:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:krisis="clr-namespace:Krisis.Controls;assembly=Krisis.Controls"
Title="MainWindow" Height="350" Width="525">
<Grid>
<krisis:AutoCompleteTextBox SearchText="Bob" Width="200" MinHeight="35" FontSize="18" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>
有人可以帮我连接这个事件处理程序,以便当我单击按钮时调用子 DropDownButton_MouseDown。
提前致谢