我創建了一個實現INotifyPropertyChanged
接口的基類。此類還包含一個通用函數SetProperty
,用於設置任何屬性的值,並在必要時引發PropertyChanged
事件。屬性與變量作爲ByRef參數
Public Class BaseClass
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Function SetProperty(Of T)(ByRef storage As T, value As T, <CallerMemberName> Optional ByVal propertyName As String = Nothing) As Boolean
If Object.Equals(storage, value) Then
Return False
End If
storage = value
Me.OnPropertyChanged(propertyName)
Return True
End Function
Protected Overridable Sub OnPropertyChanged(<CallerMemberName> Optional ByVal propertyName As String = Nothing)
If String.IsNullOrEmpty(propertyName) Then
Throw New ArgumentNullException(NameOf(propertyName))
End If
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
然後我有一個類,它應該保存一些數據。爲了簡單起見,它只包含一個屬性(在本例中)。
Public Class Item
Public Property Text As String
End Class
然後,我有第三個類從基類繼承,並使用數據保存類。這第三類應該是WPF窗口的ViewModel。
我沒有列出RelayCommand
類的代碼,因爲您可能都有自己的實現。請記住,這個類在執行命令時執行給定的函數。
Public Class ViewModel
Inherits BaseClass
Private _text1 As Item 'data holding class
Private _text2 As String 'simple variable
Private _testCommand As ICommand = New RelayCommand(AddressOf Me.Test)
Public Sub New()
_text1 = New Item
End Sub
Public Property Text1 As String
Get
Return _text1.Text
End Get
Set(ByVal value As String)
Me.SetProperty(Of String)(_text1.Text, value)
End Set
End Property
Public Property Text2 As String
Get
Return _text2
End Get
Set(ByVal value As String)
Me.SetProperty(Of String)(_text2, value)
End Set
End Property
Public ReadOnly Property TestCommand As ICommand
Get
Return _testCommand
End Get
End Property
Private Sub Test()
Me.Text1 = "Text1"
Me.Text2 = "Text2"
End Sub
End Class
然後,我有一個使用視圖模型類作爲其DataContext
我的WPF窗口。
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Text1}" Height="24" Width="100" />
<TextBox Text="{Binding Text2}" Height="24" Width="100" />
<Button Height="24" Content="Fill" Command="{Binding TestCommand}" />
</StackPanel>
</Window>
正如你所看到的,這個窗口只包含兩個文本框和一個按鈕。文本框綁定到屬性Text1
和Text2
,並且該按鈕應該執行命令TestCommand
。
當命令執行時,Text1
和Text2
都被賦予一個值。而且由於這兩個屬性都會引發PropertyChanged
事件,所以這些值應顯示在我的窗口中。
但我的窗口中只顯示「Text2」的值。
屬性Text1
的值爲「Text1」,但似乎此屬性的PropertyChanged
事件在屬性獲取其值之前引發。
有沒有辦法改變我的基類中的SetProperty
函數,在屬性獲得它的值後提升PropertyChanged
?
謝謝你的幫助。
http://stackoverflow.com/a/4520101/17034 –