【发布时间】:2019-02-08 15:45:11
【问题描述】:
我正在使用 MVVM 方法编写 WPF 应用程序,并且我正在使用 IDataErrorInfo 进行错误验证。 当我加载视图时,在不更改文本框内容的情况下检查验证,我通过以下解决了这个问题。
How to suppress validation when nothing is entered
但现在的问题是,当文本框发生变化时,我无法实现 INotifyPropertyChanged。
所以基本上我的工具有一个开始按钮、文本框和结束按钮。应用程序执行以下操作
1) The start button onclick start a timer and disable the start button
2) User provide data in textbox
3) End the timer and calulate time difference. enable the start button for the next entry.
4) The problem is here the textbox data is not refreshed while I click the startbutton again. Since the onpropertychanged is not set on the property I can't able to refresh the data.
我可以通过实现 onpropertychange 解决刷新文本框的问题,但是在我加载数据时会显示 onload 错误。
所以我想要的是禁用加载验证并在完成该过程后刷新内容。
Window.xaml
<Button IsEnabled="{Binding IsStartButtonEnabled}" Width="79" Height="19" Margin="-700,1,708.962,0" x:Name="startbutton" Command="{Binding AddNew}" Content="Start Time"/>
<Label Width="61" Height="24" Margin="-700,1,708.962,0" x:Name="StartTimeLabel" HorizontalAlignment="Left" Content="Start Time"/>
<TextBox IsEnabled="{Binding Isdisabled}" x:Name="StarttimeTextbox" Width="71" Height="24" Margin="-700,1,708.962,0" Text="{Binding ClaimNumber, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/>
<Button Command="{Binding stop }" Margin="500,0,0,0" Width="70" Height="20" VerticalAlignment="Center" IsEnabled="{Binding IsEnabledSubmit}" Content="Submit"/>
ViewModel.cs
private bool nameChanged = false;
private string claimnumber;
public string ClaimNumber
{
get { return this.claimnumber; }
set
{
this.claimnumber = value;
nameChanged = true;
//I have disabled the onpropertychanged because if I uncommented I can
//able to accomplish textbox refresh but the tool throws error when i
//load the data
// this.OnPropertyChanged("ClaimNumber");
}
}
AddNew = new RelayCommand(o => startbutton());
stop = new RelayCommand(o => stopbutton());
public void startbutton()
{
//The claimnumber should be empty whenever I click the startbutton
ClaimNumber = null;
stopWatch.Start();
dispatcherTimer.Start();
IsEnabled = true;
IsStartButtonEnabled = false;
}
public void stopbutton()
{
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}",
ts.Hours, ts.Minutes, ts.Seconds);
IsEnabled = false;
}
private string GetValidationError(string propertyName)
{
string errorMsg = null;
switch (propertyName)
{
case "ClaimNumber":
if ((nameChanged && propertyName.Equals("ClaimNumber")))
{
if (String.IsNullOrEmpty(this.claimnumber))
errorMsg = "Please provide the claimnumber";
else if (CheckInteger(claimnumber) == false)
errorMsg = "The given claimnumberis not a Number";
}
break;
}
}
【问题讨论】: