Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在WPF/MVVM中按下按钮时验证文本框_C#_Wpf - Fatal编程技术网

C# 在WPF/MVVM中按下按钮时验证文本框

C# 在WPF/MVVM中按下按钮时验证文本框,c#,wpf,C#,Wpf,我的视图中有一个文本框和一个按钮。我的视图模型中有一个ICommand方法、String序列号属性和一个IsEnabled属性 当用户单击按钮时,我想用InDatabase属性验证文本框中的序列号。如果文本框中的内容无效,我想在文本框中提出一个错误。如果文本框中的内容有效我想禁用按钮并执行命令 以下是视图: <StackPanel Width="Auto" Height="Auto" VerticalAlignment="Center" HorizontalAlignment="Cente

我的视图中有一个
文本框
和一个
按钮
。我的视图模型中有一个
ICommand
方法、
String
序列号属性和一个
IsEnabled
属性

当用户单击
按钮时,我想用
InDatabase
属性验证
文本框中的序列号。如果
文本框
中的内容无效,我想在
文本框
中提出一个错误。如果
文本框中的内容有效
我想禁用
按钮
并执行命令

以下是视图:

<StackPanel Width="Auto" Height="Auto" VerticalAlignment="Center" HorizontalAlignment="Center">
    <UniformGrid Rows="3"  >
        <TextBlock Text="This device appears to be uninitialized."/>
        <UniformGrid Rows="1" Columns="2">
            <Label>Serial Number:</Label>
            <TextBox Text="{Binding IdentifiedSerialNumber, Mode=TwoWay, ValidatesOnDataErrors=True}"></TextBox>
        </UniformGrid>
        <Button Content="Identify" Command="{Binding IdentifyCommand}" IsEnabled="{Binding CanExecuteDeviceRestoration}"/>
    </UniformGrid>
</StackPanel>

我的问题是如何绑定该行为,这样当用户单击
按钮时,
文本框
将被验证,如果失败,它将显示一条错误消息,如果它通过,
按钮
将被禁用,命令将被执行。

您需要实现IDataErrorInfo。
这将添加一个返回字符串的索引器。
如果返回空字符串,则表示没有错误。
在按下按钮之前,您可以返回一个空字符串(您可以使用一个标志)。
按下按钮后,运行验证逻辑并适当更改标志并引发IdentifiedSerialNumber的PropertyChanged事件
您可以从中学习如何实现IDataErrorInfo。

您还需要为IdentifiedSerialNumber引发PropertyChanged事件。

那么我如何通知文本框它应该显示错误?
public string IdentifiedSerialNumber 
{
    get
    {
        return this.identifiedSerialNumber;
    }
    set
    {
        this.identifiedSerialNumber = value;
    }
}

public ICommand IdentifyCommand
{
    get
    {
        return new RelayCommand(this.RelayRestoreControllerIdentity);
    }
}

public bool CanExecuteDeviceRestoration
{
    get
    {
        return canExecuteDeviceRestoration;
    }
    private set
    {
        this.canExecuteDeviceRestoration = value;
        RaisePropertyChanged("CanExecuteDeviceRestoration");
    }
}

public async void RelayRestoreControllerIdentity()
{
    await Task.Run(
    () =>
    {
        this.RestoreControllerIdentity();
    });
}

public bool InDatebase
{
    get
    {
        return DatabaseConnection.DeviceExists(this.IdentifiedSerialNumber);
    }
}