简体   繁体   English

使用WPF验证C#中的文本框

[英]Validate textbox in c# with wpf

I have a window with some textboxes, comboxes and checkboxes. 我有一个带有一些文本框,combox和复选框的窗口。 One of the textboxes need to be a number so I wanted to validate it. 文本框之一必须是数字,所以我想对其进行验证。 I searched through the internet and found a good tutorial . 我通过互联网搜索,找到了一个很好的教程 I tried to use it, but it seems that it doesn't work or I did something wrong and I just don't see what I did wrong. 我尝试使用它,但似乎不起作用,或者我做错了什么,只是看不到我做错了什么。 So I hope anyone here can say me what I'm doing wrong or an other solution to get it started. 因此,我希望这里的任何人都可以告诉我我做错了什么,或者是其他解决方案来启动它。 Here is the xaml of the window: 这是窗口的xaml:

<Window x:Class="WpfApplication1.mainpanels.EditWorkAssignments"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:validators="clr-namespace:WpfApplication1.validationRules"
    Title="EditWorkAssignments" Height="225" Width="300">
<Window.Resources>
    <Style TargetType="{x:Type TextBox}">

        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="ToolTip"
            Value="{Binding RelativeSource={RelativeSource Self}, 
                   Path=(Validation.Errors)[0].ErrorContent}"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="200" />
    </Grid.ColumnDefinitions>
    <Label Grid.Row="0" Grid.Column="0" Content="Datum:"/>
    <Label Grid.Row="1" Grid.Column="0" Content="Projekt:"/>
    <Label Grid.Row="2" Grid.Column="0" Content="Ist Passiv:"/>
    <Label Grid.Row="3" Grid.Column="0" Content="Dauer:"/>
    <Label Grid.Row="4" Grid.Column="0" Content="Mitarbeiter:"/>
    <DatePicker Name="datePicker" Grid.Column="1" Grid.Row="0" Margin="3" />
    <ComboBox Name="comboBoxProject" Grid.Column="1" Grid.Row="1" Margin="3" />
    <CheckBox Name="checkBoxIsPassiv" Grid.Column="1" Grid.Row="2" Margin="3" />
    <TextBox Name="textBoxDauer" Grid.Column="1" Grid.Row="3" Margin="3" >
        <Binding Path="workAssignment.duration" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <validators:IsNumberValidationRule ErrorMessage="Dauer has to be a number." />
            </Binding.ValidationRules>
        </Binding>
    </TextBox>
        <ComboBox Name="comboBoxEmployee" Grid.Column="1" Grid.Row="4" Margin="3">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock>
                    <TextBlock.Text>
                        <MultiBinding StringFormat="{}{0} {1}">
                            <Binding Path="firstname"/>
                            <Binding Path="surname"/>
                        </MultiBinding>
                    </TextBlock.Text>
                </TextBlock>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
    <Button Grid.Column="1" Grid.Row="5" HorizontalAlignment="Left" 
        MinWidth="80" Margin="3" Content="Save"  Click="saveHandler"/>
    <Button Grid.Column="1" Grid.Row="5" HorizontalAlignment="Right" 
        MinWidth="80" Margin="3" Content="Cancel" Click="cancelHandler" />
</Grid>

the code: 编码:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1.mainpanels
{
    /// <summary>
    /// Interaction logic for EditWorkAssignments.xaml
    /// </summary>
    public partial class EditWorkAssignments : Window
    {
        EmployeeManagementEntities1 context = null;
        public WorkAssignement workAssignment;

        public EditWorkAssignments(WorkAssignement workAssignment)
        {
            InitializeComponent();
            this.workAssignment = workAssignment;

            context = new EmployeeManagementEntities1();
            DbSet<Employee> employeeDb = context.Set<Employee>();
            employeeDb.Load();
            comboBoxEmployee.ItemsSource = employeeDb.Local;

            DbSet<Project> projectDb = context.Set<Project>();
            projectDb.Load();
            comboBoxProject.ItemsSource = projectDb.Local;
            comboBoxProject.DisplayMemberPath = "projectname";
        }


        private void saveHandler(object sender, RoutedEventArgs e)
        {
            Employee employee = (Employee)comboBoxEmployee.SelectedItem;
            Project project = (Project)comboBoxProject.SelectedItem;

            context.SaveChanges();
            Console.WriteLine("saveHandler");
        }

        private void cancelHandler(object sender, RoutedEventArgs e)
        {
            this.Close();
            Console.WriteLine("cancelHandler");
        }
    }
}

and the validationRule: 和validationRule:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Globalization;
using System.Text.RegularExpressions;

namespace WpfApplication1.validationRules
{
    public class IsNumberValidationRule : ValidationRule
    {
        private string _errorMessage;

        public string ErrorMessage
        {
            get { return _errorMessage; }
            set { _errorMessage = value; }
        }

        public override ValidationResult Validate(object value,
            CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);
            string inputString = (value ?? string.Empty).ToString();
            try
            {
                double.Parse(inputString);
            }
            catch(FormatException ex)
            {
                result = new ValidationResult(false, this.ErrorMessage);
            }
            return result;
        }
    }
}

You need to set up a ViewModel for the property bound to the textbox, textBoxDauer or create the property in your code behind, eg Duration. 您需要为绑定到文本框textBoxDauer的属性设置ViewModel ,或在后面的代码中创建属性,例如Duration。 In that property then do the validation like this 然后在该属性中进行如下验证

public string Duration 
{
    get { return _duration ; }
    set
    {
        _name = value;
        if (String.IsNullOrEmpty(value) || Int32.TryParse(value))
        {
            throw new ArgumentException("Dauer has to be a number..");
        }
    }
}

This set method is what gets called by the UpdateSourceTrigger, if an exception is thrown it will propagate up the tree and everything should work as expected. UpdateSourceTrigger调用此set方法,如果引发异常,则它将在树中传播,并且一切都将按预期工作。

Hope it helps. 希望能帮助到你。

The solution to my problem was really easl. 解决我的问题的方法确实很简单。 I just missed to set workassignment as my dataContext: 我只是想将workassignment设置为我的dataContext:

        this.DataContext = workAssignement;

Sarajog 萨拉若格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM