[英]WPF Binding Validation Rule issue
我正在开发一个简单的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;
}
使用这样的Device类:
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时阅读的不同的tuto,我应该使用类似TextBox边框的红色(默认为WPF),但是我有一个经典的“未处理的异常”
你能帮我吗?
非常感谢。
更新1:部分答案
即使我有Visual Studio“未处理的异常”,实际上我也有UI上的例外行为...所以问题是如何正确处理异常引发?
使用INotifyDataError接口确实是解决方案。
我关注了约瑟夫·哈鲁什(Jossef Harush)链接的文章: http ://hirenkhirsaria.blogspot.co.il/2013/05/wpf-input-validation-using-mvvm.html
但是,我必须实现GetErrors方法的尸体,而该方法在本教程中没有完成。
谢谢你的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.