0

我有一个带有许多控件的窗口,这些控件不受其他任何东西的约束。但是,我想应用一些特定于窗口的验证。我想我可以通过IDataErrorInfo在窗口上实现来做到这一点;并且要么实现INotifyPropertyChanged单独的控件/属性,要么在窗口上公开依赖属性并绑定到这些依赖属性(这也将允许我利用这些控件上的现有 ValueConverters)。这是可取的吗?这样做有什么缺点?

这就是我正在考虑的(XAML):

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="winInitialContact" x:Name="UC">
  <StackPanel>
    <Label Content="From" />
    <TextBox Text="{Binding FromTime, ElementName=UC, Converter={StaticResource TimeConverter}, ValidatesOnDataErrors=True}" />
    <Label Content="To" />
    <TextBox Text="{Binding ToTime, ElementName=UC, Converter={StaticResource TimeConverter}, ValidatesOnDataErrors=True}" />
  </StackPanel>
</Window>

和代码:

Imports System.ComponentModel

Class MainWindow
    Implements IDataErrorInfo
    Implements INotifyPropertyChanged

    Shared ReadOnly FromTimeProperty = DependencyProperty.Register("FromTime", GetType(TimeSpan?), GetType(MainWindow), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, Sub(s, e) DirectCast(s, MainWindow).RaisePropertyChanged("FromTime")))
    Property FromTime As TimeSpan?
        Get
            Return GetValue(FromTimeProperty)
        End Get
        Set(value As TimeSpan?)
            SetValue(FromTimeProperty, value)
        End Set
    End Property

    Shared ReadOnly ToTimeProperty = DependencyProperty.Register("ToTime", GetType(TimeSpan?), GetType(MainWindow), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, Sub(s, e) DirectCast(s, MainWindow).RaisePropertyChanged("ToTime")))
    Property ToTime As TimeSpan?
        Get
            Return GetValue(ToTimeProperty)
        End Get
        Set(value As TimeSpan?)
            SetValue(ToTimeProperty, value)
        End Set
    End Property

    Public ReadOnly Property [Error] As String Implements IDataErrorInfo.Error
        Get
            Return Nothing
        End Get
    End Property

    Default Public ReadOnly Property Item(columnName As String) As String Implements IDataErrorInfo.Item
        Get
            Select Case columnName
                Case "FromTime"
                    If Not FromTime.HasValue Then Return "Missing from time"
                Case "ToTime"
                    If Not ToTime.HasValue Then Return "Missing end time"
            End Select
            Return Nothing
        End Get
    End Property

    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged

    Sub RaisePropertyChanged(propName As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName))
    End Sub
End Class
4

0 回答 0