1

我刚刚开始使用 WPF,尤其是验证和数据绑定。

这是我的 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 和 Validations for TextBoxes 的概念来做同样的事情,请帮助我提供所需的代码

4

3 回答 3

2

这可能会帮助你

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

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

于 2013-10-22T06:56:57.317 回答
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/

于 2013-10-22T06:49:58.870 回答
1

好吧,您将需要使用 DataBinding 重写它,这是创建数据绑定的一般概述,例如:

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

所以让我解释一下,我使用以下模式将TextTextBox的属性绑定到元素tb3的以下属性,这意味着,更改 Grid 中的选定索引会影响 tb3但更改文本框中的 不会影响实际选择。有时当属性类型不匹配时,您必须使用转换器,这是一个示例:SelctedIndexGridOneWayTextTextGrid

msdn.microsoft.com

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

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

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

新: www.codeproject.com

所以问题

博客.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";
    }
}

关于 DataBinding 的有用链接:

msdn.microsoft.com

tb2在这里,我为您提供TextBox的绑定和转换器,以显示当前选定的用户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}}"/>
于 2013-10-22T06:54:36.640 回答