繁体   English   中英

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

[英]Validate a TextBox upon button press in WPF/MVVM

我的视图中有一个TextBox和一个Button 我的视图模型中有ICommand方法, String序列号属性和IsEnabled属性。

当用户单击Button我想使用InDatabase属性验证TextBox的序列号。 如果TextBox中的内容无效,我想在TextBox上引发错误。 如果内容在TextBox有效,我想禁用Button并执行命令。

这是视图:

<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>

这是视图模型:

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);
    }
}

我的问题是我该如何绑定行为,以便当用户单击ButtonTextBox得到验证;如果失败,则显示错误消息,并且如果传递则Button将被禁用,命令将执行。

您需要实现IDataErrorInfo。
这将添加一个返回字符串的索引器。
如果返回空字符串,则表示没有错误。
您可以返回一个空字符串,直到按下按钮为止(您可以使用一个标志)。
当按下按钮时,运行验证逻辑并适当更改IdentifiedSerialNumber的标志和Raise PropertyChanged事件
您可以从此处了解如何实现IDataErrorInfo。
另外,您还需要引发IdentifiedSerialNumber的PropertyChanged事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM