如何准确地通知命令以执行其CanExecute?

时间:2019-03-16 07:16:23

标签: wpf icommand

想象一下,您有一个简单的WPF窗口,上面只有一个TextBox和一个ButtonTextBox的{​​{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属性,并且此更改可能会影响ImportCommandImportCommand的启用状态一定要绑定到

WPF是否在发生的任何 FileName任何 Button上致电ImportCommand?听起来对我来说是很多不必要的工作?

1 个答案:

答案 0 :(得分:1)

RelayCommad中的CanExecuteChanged事件侦听CommandManager.InvalidateRequerySuggested方法引发的CommandManager.RequerySuggested事件。

CommandManager再次侦听InputManager KeyUp MouseUp或GotKeyboardFocus或LostKeyboardFocus事件,并调用InvalidateRequerySuggested来通知UI来调用Command的CanExecute方法。