簡體   English   中英

WPF綁定驗證規則問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM