想象一下,您有一个简单的WPF窗口,上面只有一个TextBox
和一个Button
。 TextBox
的{{1}}属性绑定到名为Text
的属性,而FileName
的{{1}}属性绑定到名为{{1}的属性}。
Button
视图模型也差不多是样板代码。
Command
ImportCommand
和<StackPanel>
<TextBox Text="{Binding FileName, UpdateSourceTrigger=PropertyChanged}" />
<Button Content="Import" Command="{Binding ImportCommand}" />
</StackPanel>
之间没有明显的联系,并且Public Class MainViewModel
Inherits ObservableItem
Private _fileName As String
Private _importCommand As ICommand = New RelayCommand(AddressOf Me.Import, AddressOf Me.CanImport)
Public Sub New()
Me.FileName = "C:\Temp\temp.dat"
End Sub
Public Property FileName As String
Get
Return _fileName
End Get
Set(value As String)
MyBase.SetProperty(Of String)(_fileName, value)
End Set
End Property
Public ReadOnly Property ImportCommand As ICommand
Get
Return _importCommand
End Get
End Property
Private Sub Import()
Throw New NotImplementedException
End Sub
Private Function CanImport() As Boolean
Return Not String.IsNullOrEmpty(Me.FileName) AndAlso IO.File.Exists(Me.FileName)
End Function
End Class
属性和TextBox
之间没有明显的联系。
因此,Button
如何检测到,我可能已经更改了FileName
属性,并且此更改可能会影响ImportCommand
,ImportCommand
的启用状态一定要绑定到
WPF是否在发生的任何 FileName
和任何 Button
上致电ImportCommand
?听起来对我来说是很多不必要的工作?
答案 0 :(得分:1)
RelayCommad中的CanExecuteChanged事件侦听CommandManager.InvalidateRequerySuggested方法引发的CommandManager.RequerySuggested事件。
CommandManager再次侦听InputManager KeyUp MouseUp或GotKeyboardFocus或LostKeyboardFocus事件,并调用InvalidateRequerySuggested来通知UI来调用Command的CanExecute方法。