基本的 WPF 验证和数据绑定

本文关键字:数据绑定 验证 WPF | 更新日期: 2023-09-27 18:36:18

我刚刚开始使用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");
    }
    }

这段代码是有效的,但我需要使用文本框的数据绑定和验证的概念来做同样的事情,请帮助我使用所需的代码

基本的 WPF 验证和数据绑定

这可能会

对你有所帮助

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

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

好吧,

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

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

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

msdn.microsoft.com

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

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

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

新增:www.codeproject.com

所以问题

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}}"/>

你需要做的 首先阅读有关 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/