基本WPF验证和DataBinding

时间:2013-10-22 06:29:50

标签: c# wpf xaml data-binding

我刚刚开始使用WPF,尤其是Validations和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");

    }

    }

这段代码正在运行,但是我需要使用DataBinding和TextBoxes验证的概念,请帮我提供所需的代码

3 个答案:

答案 0 :(得分:2)

这可能会对你有所帮助

<Binding Path="EventDate"  UpdateSourceTrigger="PropertyChanged">
   <Binding.ValidationRules>
      <ExceptionValidationRule />
   </Binding.ValidationRules>
</Binding>

你也可以参考这个链接 http://www.codeproject.com/Articles/29054/WPF-Data-Binding-Part-1

答案 1 :(得分:1)

首先需要做的是阅读MVVM。

你似乎正在使用wpf作为winforms,这会耗费大量时间。

当你读完关于mvvm的文章时(比如说在一周左右......),请阅读这些文章。

您正在寻找IDataErrorInfo:

http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/

http://tarundotnet.wordpress.com/2011/03/03/wpf-tutorial-how-to-use-idataerrorinfo-in-wpf/

答案 2 :(得分:1)

那么你可以使用DataBinding重写它,这是关于创建数据绑定的一般概述,例如:

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

让我解释一下,我已使用以下模式Text将TextBox tb3的{​​{1}}属性绑定到元素SelctedIndex的以下属性Grid ,更改网格中选定的索引将影响tb3 OneWay,但更改文本框中的Text不会影响实际的Text选择。有时,当属性类型不匹配时,您必须使用转换器,这是一个示例:

msdn.microsoft.com

一般来说,它看起来非常像这样,但请注意,你也可以在代码隐藏中绑定这些属性,但是如果你能更好地保留到xaml。

提示:如果您想使用绑定,您必须确保Grid指向属性。

最后,这里有链接,您可以查看有关验证的更多信息:

新: www.codeproject.com

SO question

blogs.msdn.com

或代码隐藏(不推荐)

Path

有关DataBinding的有用链接:

msdn.microsoft.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"; } } TextBox提供绑定和转换,以显示当前选定的用户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"

然后像这样编辑你的TextBox:

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