2013-10-22 58 views
1

我剛開始使用WPF,特別是驗證和數據綁定。基本的WPF驗證和DataBinding

這是我的XAML代碼

<Window x:Class="simpledatagrid.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 SelectionChanged="Iddetails" Name="dgsample" BorderBrush="Black" BorderThickness="2" AutoGenerateColumns="True" CanUserAddRows="True" CanUserDeleteRows="True" CanUserSortColumns="False" Margin="200,10,10,75"></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="" VerticalAlignment="Top" Width="100" /> 
    <TextBox Name="tb2" HorizontalAlignment="Left" Height="20" Margin="60,60,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/> 
    <TextBox Name="tb3" HorizontalAlignment="Left" Height="20" Margin="60,110,0,0" TextWrapping="NoWrap" Text="" 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 = "leon", Salary = 10 }); 
        Users.Add(new User() { Id = 102, Name = "allen", Salary = 20 }); 
        Users.Add(new User() { Id = 103, Name = "neon", Salary = 30 }); 
        Users.Add(new User() { Id = 104, Name = "xeln", Salary = 40 }); 
        Users.Add(new User() { Id = 105, Name = "kalen", Salary = 50 }); 
        Users.Add(new User() { Id = 106, Name = "velen", Salary = 60 }); 

        dgsample.ItemsSource = Users; 

      } 

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

     tb1.Text = Users[index].Id.ToString(); 
     tb2.Text = Users[index].Name; 
     tb3.Text = Users[index].Salary.ToString(); 

    } 
    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"); 

    } 

    } 

此代碼工作,但我使用數據綁定和驗證的概念,需要同樣的事情對於TextBoxes,請幫我使用所需的代碼

+1

你」重新使用像你一樣的WPF會做Windows窗體。我強烈建議你閱讀關於MVVM。此模式也使驗證更容易。 –

+0

一般而言,您可以通過例如'Content = {Binding Path = content ElementName = name}將控件的屬性綁定到其他控件的code-behind/property中的屬性' – Tafari

回答

1

那麼你將有一些工作使用數據綁定是在例如創建數據綁定的總體概述它改寫:

<TextBox Name="tb3" HorizontalAlignmentText="{Binding Path=SelectedIndex, ElementName=Grid, , Mode=OneWay}"/> 

所以讓我解釋一下,我已經綁定Text屬性o f TextBox tb3添加到元素Grid的以下屬性SelctedIndex使用以下模式OneWay這意味着,更改網格中選定的索引將影響tb3 Text,但在文本框中更改Text不會影響實際的Grid選擇。有時,當屬性類型不匹配,你必須在這裏使用一個轉換器就是一個例子:

msdn.microsoft.com

一般來說它看起來很像這樣,但是請注意,你也可以在綁定的代碼 - propierties後面,但如果你可以更好地留在xaml。

提示:如果您想使用綁定,您必須確保Path指向屬性。

最後這裏有關於驗證的詳細信息的鏈接,你應該檢查出:

新:www.codeproject.com

SO question

blogs.msdn.com

或代碼隱藏(不推薦)

private void tb1_TextChanged(object sender, TextChangedEventArgs e) 
{ 
    int output; 
    if (!int.TryParse(tb1.Text, out output)) 
    { 
     MessageBox.Show("Enter valid int."); 
     tb1.Text = "0"; 
    } 
} 

有關數據綁定有用的鏈接:

msdn.microsoft.com

在這裏,我向您提供結合和轉換器tb2文本框,顯示當前選擇的用戶name

這個類添加到您的命名空間:

using System; 
using System.Globalization; 
using System.Windows.Data; 

namespace WpfApplicationTest 
{ 
[ValueConversion(typeof(object), typeof(String))] 
public class MyConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     string name = ""; 
     if (value != null) 
     { 
      User user = (User)value; 
      name = user.Name; 
     } 
     else 
     { 
      name = ""; 
     } 

     return name; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return null; 
    } 
} 
} 

然後添加到您的窗口:

xmlns:myNamespace="clr-namespace:WpfApplicationTest"

<Window.Resources> 
    <myNamespace:MyConverter x:Key="myConverter"/> 
</Window.Resources> 

那麼這樣的編輯文本框:

<TextBox Name="tb2" Text="{Binding Path=SelectedItem, ElementName=Grid, Mode=OneWay, Converter={StaticResource myConverter}}"/> 
+0

@ user2889489我已經爲您添加了一些其他代碼,將tb2綁定到當前選定的用戶名。檢查我的答案是否爲'NEW'鏈接,我認爲它應該足夠清楚,以便您瞭解它。如果可以請upvote我的答案,以及歡呼! – Tafari

+0

@ user2889489我給你三個鏈接使用這個在xaml驗證:http://www.codeproject.com/Articles/15239/Validation-in-Windows-Presentation-Foundation或通過代碼隱藏 – Tafari

+0

@ user2889489我會看看它。 – Tafari