Creating Generic DropDown Control in WPF

Creating Generic DropDown Control in WPF

Following code snippet shows how to create a custom DropDown control in WPF.


Imports System.Windows.Controls.Primitives
Imports System.ComponentModel
 
Public Class DropDownControl
    Inherits System.Windows.Controls.Primitives.ToggleButton
 
    Shared Sub New()
        'This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class.
        'This style is defined in themes\generic.xaml
        DefaultStyleKeyProperty.OverrideMetadata(GetType(DropDownControl), New FrameworkPropertyMetadata(GetType(DropDownControl)))
    End Sub
 
    Public Sub New()
        Popup = New Popup()
        Popup.StaysOpen = False
        Me.SetBinding(IsCheckedProperty, "Popup.IsOpen")
    End Sub
 
    Public Property Popup As Popup
        Get
            Return GetValue(PopupProperty)
        End Get
 
        Set(ByVal value As Popup)
            SetValue(PopupProperty, value)
        End Set
    End Property
 
    Public Shared ReadOnly PopupProperty As DependencyProperty = _
                           DependencyProperty.Register("Popup", _
                           GetType(Popup), GetType(DropDownControl), _
                           New FrameworkPropertyMetadata(Nothing))
 
    Public Property DropDown As FrameworkElement
        Get
            Return GetValue(DropDownProperty)
        End Get
 
        Set(ByVal value As FrameworkElement)
            SetValue(DropDownProperty, value)
        End Set
    End Property
 
    Public Shared ReadOnly DropDownProperty As DependencyProperty = _
                           DependencyProperty.Register("DropDown", _
                           GetType(FrameworkElement), GetType(DropDownControl), _
                           New FrameworkPropertyMetadata(NothingNew PropertyChangedCallback(AddressOf OnDropDownChanged)))
 
    Private Shared Sub OnDropDownChanged(ByVal d As System.Windows.DependencyObjectByVal e As System.Windows.DependencyPropertyChangedEventArgs)
        Dim ddc As DropDownControl = d
        If ddc.Popup IsNot Nothing Then
            ddc.Popup.Child = e.NewValue
        End If
    End Sub
 
    Protected Overrides Sub OnClick()
        MyBase.OnClick()
        Popup.PlacementTarget = Me
        Popup.Placement = PlacementMode.Bottom
        Popup.IsOpen = True
    End Sub
 
End Class

Kategori

Kategori