我为一些管理任务编写了WPF用户应用程序,并最终准备好了……直到最后一个问题:
我有2个TextBox控件,但我不想让用户同时填写两者,所以我做到了:
private string versichertennummerAlt = "";
public string VersichertennummerAlt
{
get { return versichertennummerAlt; }
set
{
if (Versichertennummer.Length > 0)
{
versichertennummerAlt = "";
OnPropertyChanged("VersichertennummerAlt");
throw new ArgumentException("Es kann nur die neue ODER die alte Versichertennummer eingegeben werden.\n Eine von beiden löschen.");
}
........
}
}
它应该如何工作,如果用户尝试同时填充两个字符串,我会得到一个异常,字符串为“”,但是不知何故该文本框仍显示最后按下的键,即使该属性为“”。
我究竟做错了什么?或者我如何确保TextBox在异常后没有显示任何内容?
感谢您的帮助:)
您不希望以这种方式使用异常,除非您将其捕获到某个地方并进行处理。在文本框中输入文本绝对不会致命。除此之外,我认为按照注释中的建议进行操作是个好主意,也就是说,IsEnabled="False"
如果另一个文本框内有文本,则创建一个文本框,反之亦然:
XAML:
<TextBox x:Key="TextBoxA"
IsEnabled="{Binding IsTextBoxAEnabled}"
Text="{Binding TextA}"/>
<TextBox x:Key="TextBoxB"
IsEnabled="{Binding IsTextBoxBEnabled}"
Text="{Binding TextB}"/>
CS:
private string textA;
public string TextA
{
get { return textA; }
set
{
if (textA == value)
return;
textA = value;
this.IsTextBoxBEnabled = String.IsNullOrEmpty(textA);
OnPropertyChanged("TextA");
}
}
private bool isTextBoxAEnabled;
public bool IsTextBoxAEnabled
{
get { return isTextBoxAEnabled; }
set
{
if (isTextBoxAEnabled == value)
return;
isTextBoxAEnabled = value;
OnPropertyChanged("IsTextBoxAEnabled");
}
}
您还需要为此TextBoxB
。上面的应该禁用一个当另一个有文本...
编辑
为了解决您的意见,以防红bore等,您想实施 IDataErrorInfo
#region IDataErrorInfo Implementation.
/// <summary>
/// Access to the error.
/// </summary>
string IDataErrorInfo.Error
{
get { return String.Empty; }
}
/// <summary>
/// Get the validation error.
/// </summary>
/// <param name="propertyName">The name of the property to validate.</param>
/// <returns>The error information as a string.</returns>
string IDataErrorInfo.this[string propertyName]
{
get { return ExecuteValidation(); }
}
/// <summary>
/// Run validation routines.
/// </summary>
/// <returns>Error message.</returns>
private string ExecuteValidation()
{
// Put validation for the other TextBox here.
return String.Empty;
}
#endregion // IDataErrorInfo Implementation.
像这样使用:
<TextBox Text="{Binding SomeTextProperty,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True,
NotifyOnValidationError=True}"/>
然后,当验证失败时,将突出显示错误。
我希望这有帮助。
笔记。为了上述工作,您将需要实施INotifyPropertyChanged
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句