带有IDataErrorInfo的WPF禁用按钮

时间:2014-03-18 12:17:54

标签: wpf vb.net icommand

我找到this tutorial并且我能够实现它。

如何在发生错误时禁用按钮?

我在网上搜索了很多,但我找不到类似于我的代码。 (是的,我知道关于这个问题有很多线索,但我不理解它。)

这是我目前的代码,它有点冗长:

Public Class GradeVm
    Implements IDataErrorInfo

    Public Interface IDataErrorInfo
        Default ReadOnly Property Item(columnName As String) As String
        ReadOnly Property [Error]() As String
    End Interface

    #Region "Properties"
    Property Grade As Integer
    Property Adjust As Integer
    #End Region

    Public ReadOnly Property [Error] As String Implements IDataErrorInfo.Error
        Get
            Return "Error"
        End Get
    End Property

    Default Public ReadOnly Property Item(columnName As String) As String Implements IDataErrorInfo.Item
        Get
            Select Case columnName
                Case "Grade"
                    If IsNumeric(Me.Grade) = False Then
                        Return [Error]
                    End If
                Case "Adjust"
                    If IsNumeric(Me.Adjust) = False Then
                        Return [Error]
                    End If
            End Select

            Return ""
        End Get
    End Property
    End Class

2 个答案:

答案 0 :(得分:1)

This结合这里的代码就行了!最后!! :)

答案 1 :(得分:0)

如果您将按钮绑定到RelayCommand,则可以通过将CanExecute()功能设置为False来禁用该按钮:

Public Function CanExecute(parameter As Object) As Boolean Implements ICommand.CanExecute
    Return False
End Function

RelayCommand并不意味着以这种方式使用。我建议选择一个MVVM框架(例如MVVMLight),然后您就可以使用更好的RelayCommand实现了。然后你可以像这样使用它:

Private _myCommand As RelayCommand = New RelayCommand(Me.ExecuteCommand, Me.CanExecuteCommand)
Public ReadOnly Property MyCommand As ICommand
    Get
        Return Me._myCommand
    End Get
End Property

Private Sub ExecuteCommand()
    ......
End Sub

Private Function CanExecuteCommand() As Boolean
    'do logic to disable (return false) or enable (return true) button
    'based on specific criteria
    'just for example, disable the button forever :
    Return False
End Function

更新:

为什么删除了RelayCommand实施?第一种方法意味着,在原始帖子中使用RelayCommand,但将CanExecute()函数的返回值更改为False而不是True。然后你可以像ViewModel一样使用它:

Private _myCommand As RelayCommand = New RelayCommand()
Public ReadOnly Property MyCommand As ICommand
    Get
        Return Me._myCommand
    End Get
End Property