Imports System.ComponentModel


Public Class TextBox2nd
    Inherits System.Windows.Controls.TextBox

    Shared Sub New()
        'この OverrideMetadata 呼び出しは、この要素が基本クラスと異なるスタイルを提供することをシステムに通知します。
        'このスタイルは themes\generic.xaml に定義されています
        DefaultStyleKeyProperty.OverrideMetadata(GetType(TextBox2nd), New FrameworkPropertyMetadata(GetType(TextBox)))
    End Sub

#Region "日付"

    Public Shared ReadOnly DateValueProperty As DependencyProperty = DependencyProperty.Register( _
          "DateValue", _
          GetType(Date?), _
          GetType(TextBox2nd), _
           New PropertyMetadata(New PropertyChangedCallback(AddressOf OnDateChanged)))

    Public Property DateValue() As Date?
        Get
            Return DirectCast(GetValue(DateValueProperty), Date?)
        End Get
        Set(ByVal value As Date?)
            SetValue(DateValueProperty, value)

        End Set
    End Property

    Private Shared Sub OnDateChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
        Dim textbox2 As TextBox2nd = DirectCast(d, TextBox2nd)
        If DirectCast(e.NewValue, Date?).HasValue Then
            textbox2.SetValue(TextBox2nd.TextProperty, DirectCast(e.NewValue, Date?).Value.ToString("yyyy/MM"))
        Else
            textbox2.SetValue(TextBox2nd.TextProperty, String.Empty)
        End If
    End Sub

#End Region

    Private Sub TextBox2nd_LostFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.LostFocus
        Dim dt As Date
        If Date.TryParse(Me.Text, dt) Then
            Me.DateValue = dt
        Else
            Me.DateValue = Nothing
            'なぜかTextが空のときにこっちに来るとOnDateChangedが走らないので。
            Me.Text = String.Empty
        End If
    End Sub
End Class