WPF绑定验证规则问题

时间:2014-04-16 14:13:12

标签: c# wpf validation xaml binding

我正在开发一个简单的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时读取的不同tutos,我应该有类似TextBox边框红色(WPF默认值)的东西,但我得到了经典&#34;未处理的异常&#34;

你能帮帮我吗?

非常感谢。

更新1:答案的一部分

即使我有Visual Studio&#34;未处理的异常&#34;我实际上在UI上有例外行为...... 所以问题是如何正确管理异常抛出?

1 个答案:

答案 0 :(得分:1)

使用INotifyDataError接口确实是解决方案。

我跟着Jossef Harush链接的文章:http://hirenkhirsaria.blogspot.co.il/2013/05/wpf-input-validation-using-mvvm.html

但是我必须实现GetErrors方法的尸体,这在教程中没有完成。

感谢您的帮助!