2013-02-11 35 views
1

我想在按下某個鍵時驗證文本框中的文本。這裏是最短的代碼示例顯示了我想要做的事:UpdateSourceTrigger不工作?

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <TextBox FontSize="15" HorizontalAlignment="Left" Name="txtEmail" VerticalAlignment="Top" Width="135" 
       Text="{Binding ValidationRules.EmailAddress, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}"/> 
    </Grid> 
</Window> 

「ValidationRules」類:

當我開始在文本框中鍵入,我不明白「設置」作爲控制檯輸出,儘管我使用的是UpdateSourceTrigger=PropertyChanged。我已經完成了我的研究,但我能找到的所有例子都是漫長而混亂的。如果你能指出我在驗證過程中遇到的其他錯誤,我也會很感激,但如果可能,請嘗試用簡單的術語來解釋,因爲我是WPF的新手。

+0

是在即時窗口,有什麼錯誤? – alu 2013-02-11 23:53:26

+0

你在哪裏設置'DataContext'到'ValidationRules'類 – 2013-02-12 00:00:45

回答

2

它必須是您設置DataContext的位置的問題。

這個例子似乎很好地工作:

代碼:

public partial class MainWindow : Window, INotifyPropertyChanged 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     ValidationRules = new ValidationRules(); 
    } 

    private ValidationRules _validation; 
    public ValidationRules ValidationRules 
    { 
     get { return _validation; } 
     set { _validation = value; NotifyPropertyChanged("ValidationRules"); } 
    } 


    public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyPropertyChanged(string property) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(property)); 
     } 
    } 
} 

public class ValidationRules : INotifyPropertyChanged 
{ 
    string email = ""; 
    public string EmailAddress 
    { 
     get 
     { 
      return email; 
     } 

     set 
     { 
      Console.WriteLine("Setting!"); 
      //Only check if there is any text for now... 
      if (String.IsNullOrWhiteSpace(value)) 
      { 
       throw new Exception(); 
      } 
      email = value; 
      NotifyPropertyChanged("EmailAddress"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyPropertyChanged(string property) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(property)); 
     } 
    } 

} 

的XAML

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     x:Class="WpfApplication1.MainWindow" 
     Title="MainWindow" Height="125.078" Width="236.441" x:Name="UI" > 
    <Grid DataContext="{Binding ElementName=UI}"> 
     <TextBox FontSize="15" HorizontalAlignment="Left" Name="txtEmail" VerticalAlignment="Top" Width="135" 
       Text="{Binding ValidationRules.EmailAddress, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}"/> 
    </Grid> 
</Window> 
+0

謝謝。但是,當我使用「拋出新的Exception()」時,它會暫停執行(「異常未被用戶代碼處理」)。是否有一些你可以拋出的錯誤,但是仍然沒有達到預期的效果,還是有另一種方法去做? – Harry 2013-02-12 10:38:40

相關問題