2013-10-22 89 views
-3

我在window.When 3個文本框我輸入錯誤charecters到文本框,它應該通過validations.I'm在WPF這樣顯示錯誤,請幫助我的代碼驗證在WPF

這是我的XAML代碼

<Window x:Class="DataGrid_DataBinding.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="IDDATA" Height="350" Width="525"> 

<Grid> 
    <DataGrid AutoGeneratingColumn="DG1_AutoGeneratingColumn" Name="dgsample" BorderBrush="Black" BorderThickness="2" AutoGenerateColumns="True" CanUserAddRows="True" CanUserDeleteRows="True" CanUserSortColumns="False" Margin="200,10,10,75"> 
     <DataGrid.Columns> 
      <DataGridTextColumn Header="Id" Visibility="Hidden" Binding="{Binding Path=Id}" /> 
      <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" /> 
      <DataGridTextColumn Header="Salary" Binding="{Binding Path=Salary}" /> 
     </DataGrid.Columns> 
    </DataGrid> 

    <Label Content="ID :" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="26" Width="27"/> 
    <Label Content="Name :" HorizontalAlignment="Left" Margin="10,60,0,0" VerticalAlignment="Top" Height="26" Width="48"/> 
    <Label Content="Salary :" HorizontalAlignment="Left" Margin="10,110,0,0" VerticalAlignment="Top" Height="26" Width="47"/> 

    <TextBox Name="tb1" HorizontalAlignment="Left" Height="20" Margin="60,10,0,0" TextWrapping="NoWrap" Text="{Binding SelectedItem.Id, ElementName=dgsample,ValidatesOnNotifyDataErrors=True,ValidatesOnExceptions=True,NotifyOnValidationError=True,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="100" /> 

    <TextBox Name="tb2" HorizontalAlignment="Left" Height="20" Margin="60,60,0,0" TextWrapping="NoWrap" Text="{Binding SelectedItem.Name, ElementName=dgsample,ValidatesOnNotifyDataErrors=True,ValidatesOnExceptions=True,NotifyOnValidationError=True}" VerticalAlignment="Top" Width="100"/> 
    <TextBox Name="tb3" HorizontalAlignment="Left" Height="20" Margin="60,110,0,0" TextWrapping="NoWrap" Text="{Binding SelectedItem.Salary, ElementName=dgsample,ValidatesOnNotifyDataErrors=True,ValidatesOnExceptions=True,NotifyOnValidationError=True}" VerticalAlignment="Top" Width="100"/> 

    <Button Content="Get" HorizontalAlignment="Left" Margin="10,190,0,0" VerticalAlignment="Top" Width="75" Click="Get_Click" /> 
    <Button Content="Add" HorizontalAlignment="Left" Margin="10,230,0,0" VerticalAlignment="Top" Width="75" Click="Add_Click" /> 
    <Button Content="Delete" HorizontalAlignment="Left" Margin="10,270,0,0" VerticalAlignment="Top" Width="75" Click="Delete_Click" /> 
</Grid> 

這是的.cs代碼

public partial class MainWindow : Window 
{ 
    ObservableCollection<User> Users = new ObservableCollection<User>(); 
    public MainWindow() 
    { 
     InitializeComponent(); 

     Users.Add(new User() { Id = 101, Name = "allen", Salary = 10 }); 
     Users.Add(new User() { Id = 102, Name = "scott", Salary = 20 }); 
     Users.Add(new User() { Id = 103, Name = "mickey", Salary = 30 }); 
     Users.Add(new User() { Id = 104, Name = "micheal", Salary = 40 }); 
     Users.Add(new User() { Id = 105, Name = "fletch", Salary = 50 }); 
     Users.Add(new User() { Id = 106, Name = "etcher", Salary = 60 }); 

     dgsample.ItemsSource = Users; 

    } 
    private void DG1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) 
    { 
     switch (e.Column.Header.ToString()) 
     { 
      case "Id": 

       e.Column.Visibility = Visibility.Hidden; 
       break; 
      case "Name": 
       e.Column.Visibility = Visibility.Hidden; 
       break; 
      case "Salary": 
       e.Column.Visibility = Visibility.Hidden; 
       break; 
     } 
    } 

    private void Get_Click(object sender, RoutedEventArgs e) 
    { 


     int index; 
     if (int.TryParse(this.tb1.Text, out index)) 
     { 
      User currentUser = Users.FirstOrDefault(Select => Select.Id == int.Parse(tb1.Text)); 
      if (currentUser != null) 
      { 
       this.tb2.Text = currentUser.Name; 
       this.tb3.Text = currentUser.Salary.ToString(); 
      } 
      else 
       MessageBox.Show("User with the provided ID does not Exist", "Error"); 
     } 
     else 
      MessageBox.Show("ID entered is not valid number", "Error"); 





    } 



    private void Add_Click(object sender, RoutedEventArgs e) 
    { 


     if (!tb1.Text.Equals("")) 
     { 
      var adduser = Users.Where(User => User.Id == int.Parse(tb1.Text)); 

      if (!adduser.Any()) 
      { 
       Users.Add(new User() { Id = int.Parse(tb1.Text), Name = tb2.Text, Salary = int.Parse(tb3.Text) }); 
      } 

      else 

       MessageBox.Show("Someone already has that ID."); 

     } 

    } 

    private void Delete_Click(object sender, RoutedEventArgs e) 
    { 
     int index; 
     if (int.TryParse(this.tb1.Text, out index)) 
     { 
      User currentUser = Users.FirstOrDefault(Select => Select.Id == int.Parse(tb1.Text)); 
      if (currentUser != null) 
      { 
       Users.Remove(currentUser); 
      } 
      else 
       MessageBox.Show("User with the provided ID does not Exist", "Error"); 
     } 
     else 
      MessageBox.Show("ID entered is not valid number", "Error"); 

    } 

} 
+1

那麼什麼是你的代碼的問題?你有什麼問題? – Sheridan

回答

1

你可以在這裏找到答案:

stackoverflow.com

最簡單的將是這樣的:

首先您User類實現IDataErrorInfo,所以會更或這樣少的樣子:

public class User : IDataErrorInfo, INotifyPropertyChanged 
{ 
    private int id; 
    public int Id 
    { 
     get 
     { 
      return id; 
     } 
     set 
     { 
      id = value; 
      OnPropertyChanged("Id"); 
     } 
    } 
    private string name; 
    public string Name 
    { 
     get 
     { 
      return name; 
     } 
     set 
     { 
      name = value; 
      OnPropertyChanged("Name"); 
     } 
    } 
    private int salary; 
    public int Salary { 
     get 
     { 
      return salary; 
     } 
     set 
     { 
      salary = value; 
      OnPropertyChanged("Salary"); 
     } 
    } 

    public string Error 
    { 
     get 
     { 
      return null; 
     } 
    } 

    public string this[string columnName] 
    { 
     get 
     { 
      string result = null; 
      if (columnName == "Name") 
      { 
       if (string.IsNullOrEmpty(Name)) 
       { 
        result = "Please enter a First name"; 
       } 
      } 
      if (columnName == "Salary") 
      { 
       if (Salary <= 0) 
       { 
        result = "Please enter a valid salary"; 
       } 
      } 
      if (columnName == "Id") 
      { 
       if (Id < 0) 
       { 
        result = "Please enter a valid id"; 
       } 
      } 
      return result; 
     } 
    } 

    public User() 
    { 

    } 

    public User(int id, string name, int salary) 
    { 
     Id = id; 
     Name = name; 
     Salary = salary; 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    [NotifyPropertyChangedInvocator] 
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

然後在創建屬性您MainWindow.xaml.cs file:

private User currUser; 
public User CurrUser { get; set; } 

而只是爲了ee值,它工作在構造函數中添加:

public MainWindow() 
{ 
    CurrUser = new User(); 
    InitializeComponent(); 
} 

MainWindow.xaml添加到您的Window

<Window 
Name="myWindow" 
... 

最後,您可以將您的TextBoxes這樣的:

<TextBox Name="tb1" Height="23" Margin="51,191,0,0" Width="120" Text="{Binding Path=CurrUser.Id, ElementName=myWindow, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=true, NotifyOnValidationError=true}"/> 
<TextBox Name="tb2" Height="23" Margin="51,219,0,0" Width="120" Text="{Binding Path=CurrUser.Name, ElementName=myWindow, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=true, NotifyOnValidationError=true}"/> 
<TextBox Name="tb3" Height="23" Margin="50,163,0,0" Width="120" Text="{Binding Path=CurrUser.Salary, ElementName=myWindow, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=true, NotifyOnValidationError=true}"/> 

現在,如果User類中的條件將不會被TextBoxe.Text滿足,它們的邊界將變爲紅色,這說明存在val idation問題。

Validation screen

編輯從問題所有者

而且使用的驗證與在DataGrid中連接到當前選擇的項目文本框要求您可以添加的SelectionChanged事件到網格並執行它:

private void dgsample_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    int index = dgsample.SelectedIndex; 

    CurrUser.Id = users[index].Id; 
    CurrUser.Salary = users[index].Salary; 
    CurrUser.Name = users[index].Name; 
} 

但是要通知文本框有關屬性更改,您必須對類進行一些額外的更改(在答案的開頭更新代碼)用戶類。

電網 definitione:

XAML

<DataGrid Name="Grid" HorizontalAlignment="Left" Margin="326,10,0,0" VerticalAlignment="Top" RenderTransformOrigin="-0.083,-1.154" Height="140" Width="181" FontStyle="Normal" SelectionChanged="Grid_SelectionChanged"> 

代碼隱藏 - 主窗口構造

public MainWindow() 
{ 
    CurrUser = new User(); 
    users = new ObservableCollection<User>(); 
    users.Add(new User() { Id = 101, Name = "gin", Salary = 10 }); 
    users.Add(new User() { Id = 102, Name = "alen", Salary = 20 }); 
    users.Add(new User() { Id = 103, Name = "scott", Salary = 30 }); 
    users.Add(new User() { Id = 104, Name = "a", Salary = 30 }); 

    InitializeComponent(); 
    Grid.ItemsSource = users; 
} 

說實話,所有你需要可以在這裏找到:

www.codeproject.com

codeblitz.wordpress.com

+0

基於異常的驗證是最差的功能。甚至不知道微軟爲什麼要這麼做。不要使用異常來強制執行業務規則,特別是用戶輸入。輸入'A'而不是'1'真的是失敗狀態? – Gusdor

+0

@ user2889489是的,我更新了我的答案,對於這個解決方案,您將不得不創建3個屬性來存儲當前「選定的項目」的值,此外,您還必須將'SelectionChanged'事件添加到'DataGrid'以更新這些屬性。 – Tafari

+0

@Gusdor這是downvote的原因?你真的希望我給他提供完整的驗證規則嗎?如上所述,這是驗證的簡單方法,我還向他提供了更多信息的鏈接,因此答案不實用。無論如何,我已經改變了答案,不要使用例外。 – Tafari