您可能需要将绑定模式设置为TwoWay
,例如:
{Binding myData, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}
我发现显式设置模式可以更好地保证数据到达 ViewModel。以下简单示例有效。
考虑这个 ViewModel 类:
Imports System.ComponentModel
Public Class VM
Implements INotifyPropertyChanged
Private _myData As String
Public Property myData As String
Get
Return _myData
End Get
Set(ByVal value As String)
_myData = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("myData"))
End Set
End Property
Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
Public Sub New()
myData = "StartingData"
End Sub
End Class
然后,包含此 XAML 的窗口(省略标头):
<Window.Resources>
<local:VM x:Key="ViewModel"/>
</Window.Resources>
<Grid DataContext="{StaticResource ViewModel}">
<StackPanel>
<TextBlock Text="{Binding myData}" />
<TextBox Text="{Binding myData, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<Button Click="Button_Click">Second Window</Button>
</StackPanel>
</Grid>
而这段代码:
Class MainWindow
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim n = New SecondWindow
n.DataContext = Me.FindResource("ViewModel")
n.Show()
End Sub
End Class
使用以下内容定义了 SecondWindow 类:
<Grid>
<TextBlock Text="{Binding myData}"/>
</Grid>
该按钮实例化 SecondWindow,将 DataContext 设置为 MainWindow 的“ViewModel”资源,这就是您所需要的。