【发布时间】:2023-03-25 23:10:01
【问题描述】:
我正在开发一个简单的 WPF 应用程序,但我被困在一些我确信非常简单的东西上,但即使经过多次搜索我也找不到解决方案。
问题是关于 TextBox Text 属性绑定的验证规则。
我想在文本框中输入的文本未经验证时生成一条消息。
我关注了关于该主题的这两页:
http://msdn.microsoft.com/fr-fr/library/ms752347(v=vs.110).aspx
http://www.codeproject.com/Articles/15239/Validation-in-Windows-Presentation-Foundation
但我找不到我错的地方。
这是我的代码示例:
XAML 部分:
<TextBox x:Name="deviceIPAddressTextBox" HorizontalAlignment="Left" Height="23" Margin="109,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" FontStyle="Italic">
<TextBox.Text>
<Binding Path="Address" UpdateSourceTrigger="LostFocus" Mode="TwoWay">
<Binding.ValidationRules>
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
代码部分:
public partial class MainWindow : Window
{
public Device CurrentDevice;
public MainWindow()
{
CurrentDevice = new Device();
InitializeComponent();
deviceIPAddressTextBox.DataContext = CurrentDevice;
}
像这样的设备类:
public class Device : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _Address;
public string Address
{
get { return _Address; }
set
{
if (string.IsNullOrEmpty(value)
{
_Address = "Enter IP Address";
OnPropertyChanged("Address");
return;
}
IPAddress ipAddress;
if (IPAddress.TryParse(value, out ipAddress))
{
_Address = value;
OnPropertyChanged("Address");
}
else
{
throw new ApplicationException("Not valid IP");
}
}
}
public Device()
{
Address = "Enter IP Address";
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
按照我在触发 ApplicationException 时阅读的不同教程,我应该有类似 TextBox 边框红色(WPF 默认)的东西,但我有一个经典的“未处理异常”
你能帮我解决这个问题吗?
非常感谢。
更新 1:部分答案
即使我有 Visual Studio“未处理的异常”,我实际上在 UI 上也有异常行为...... 所以问题是如何正确管理异常抛出?
【问题讨论】:
-
您关注的文章是旧的。看看hirenkhirsaria.blogspot.co.il/2013/05/…
-
谢谢你,Jossef 我会点击链接并让你更新我的问题。
-
使用 INotifyDataError 接口确实是解决方案。但是我必须实现本教程中没有完成的 GetErrors 方法的尸体。
-
太好了,将其发布为您问题的答案 :)
-
完成了谢谢你:)
标签: c# wpf validation xaml binding