我可以使用泛型来简化Wpf应报告的绑定吗?

时间:2010-11-21 20:59:49

标签: wpf vb.net generics binding inotifypropertychanged

我可以将VB.Net的泛型用于简单的Wpf通知绑定控件吗?

1 个答案:

答案 0 :(得分:0)

以下是如何使用VB.Net的Generics创建可通知的绑定控件。

Class MainWindow

Public Sub New()

    InitializeComponent()

    Me.DataContext = Me

End Sub

Public Property NoNotify As String = "No notify"
Public Property DoesNotify As New NotifiableProperty(Of String)("DoesNotify")

Private Sub TestBtn_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles TestBtn.Click
    NoNotify = "Won't Show"
    DoesNotify.Value = "Notified!"
End Sub

End Class

Public Class NotifiableProperty(Of T)
    Implements System.ComponentModel.INotifyPropertyChanged
Sub New()
End Sub
Sub New(ByVal InitialValue As T)
    value = InitialValue
End Sub
Private m_Value As T
Public Property Value As T
    Get
        Return m_Value
    End Get
    Set(ByVal value As T)
        m_Value = value
        RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs("Value"))
    End Set
End Property
    Private Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
End Class

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <Button Name="TestBtn" Content="Click to Test" Width="72" />
            <TextBox Name="NoNotifyTB" Text="{Binding NoNotify}" />
            <TextBox Name="DoesNotifyTB" Text="{Binding DoesNotify.Value}"/>
        </StackPanel>
    </Grid>
</Window>