[英]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);
}
}
我的問題是我該如何綁定行為,以便當用戶單擊Button
, TextBox
得到驗證;如果失敗,則顯示錯誤消息,並且如果傳遞則Button
將被禁用,命令將執行。
您需要實現IDataErrorInfo。
這將添加一個返回字符串的索引器。
如果返回空字符串,則表示沒有錯誤。
您可以返回一個空字符串,直到按下按鈕為止(您可以使用一個標志)。
當按下按鈕時,運行驗證邏輯並適當更改IdentifiedSerialNumber的標志和Raise PropertyChanged事件
您可以從此處了解如何實現IDataErrorInfo。
另外,您還需要引發IdentifiedSerialNumber的PropertyChanged事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.