2017-06-06 52 views
0

更新:我通過改進我的switch語句來解決此問題。使用名稱的WPF iDataErrorInfo(驗證文本框)不按預期工作

我想從文本框中驗證一組用戶輸入。

我有我的課程與接口設置。下面的這片段:

public class PatientValidation : INotifyPropertyChanged, IDataErrorInfo 
    { 
     private string _id; 
     private string _fname; 

     public event PropertyChangedEventHandler PropertyChanged; 

     private void OnPropertyChanged(string p) 
     { 
      PropertyChangedEventHandler ph = PropertyChanged; 
      if (ph != null) 
      { 
       ph(this, new PropertyChangedEventArgs(p)); 
      } 

     } 

     public string Id 
     { 
      get 
      { 
       return _id; 
      }  
      set 
      { 
       _id = value; 
      } 
     } 
     public string Fname 
     { 
      get 
      { 
       return _fname; 
      }  
      set 
      { 
       _fname = value; 
      } 
     } 

而且switch語句基於用戶輸入返回的錯誤信息:

public string this[string PropertyName] 
     { 
      get 
      { 
       string result = null; 

       switch (PropertyName) 
       { 
        case "Id": 
         if (string.IsNullOrEmpty(Id)) 
          result = "ID number is required."; 
         break; 

        case "fname": 
         if (string.IsNullOrEmpty(Fname)) 
          result = "First name is required."; 
         break; 
        } 
        return result; 
      } 
      } 

我在XAML相關代碼:

<Style TargetType="TextBox"> 
      <Style.Triggers> 
       <Trigger Property="Validation.HasError" Value="true"> 
        <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}"/> 
       </Trigger> 
      </Style.Triggers> 
     </Style> 

<TextBox x:Name="textBox_IDNumber" Text="{Binding Id, Mode=TwoWay, ValidatesOnDataErrors=True}"/> 
<TextBox x:Name="textBox_FirstName" Text="{Binding Fname, Mode=TwoWay, ValidatesOnDataErrors=True"}/> 

這裏是我的問題已經遇到:只有第一個文本框(ID)被正確驗證,並顯示錯誤工具提示。沒有其他的文本框。 不同的綁定和觸發器尚未解決問題。任何幫助將非常感激。

回答

0

錯字錯誤(你使用你的交換機小寫):

case "fname": 

但在你的綁定:

Text="{Binding Fname 
0

它似乎沒有要調用的制定者中OnPropertyChanged(nameof(FName));OnPropertyChanged(nameof(ID));您的屬性 - 因此不會有通知綁定已更新,並且不會調用IDataErrorInfo.<propertyName>