使用 wpf 验证 c# 中的文本框



我有一个窗口,里面有一些文本框、组合框和复选框。其中一个文本框需要是一个数字,所以我想验证它。我在网上搜索并找到了一个很好的教程。我尝试使用它,但似乎它不起作用,或者我做错了什么,我只是看不出我做错了什么。所以我希望这里的任何人都可以告诉我我做错了什么或其他解决方案来开始它。这是窗口的 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>

代码:

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

和验证规则:

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

您需要为绑定到文本框的属性 textBoxDauer 设置一个 ViewModel,或者在代码隐藏中创建属性,例如 Duration。在该属性中,然后像这样进行验证

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

这个 set 方法就是 UpdateSourceTrigger 调用的方法,如果抛出异常,它将沿树向上传播,一切都应该按预期工作。

希望对您有所帮助。

我的问题的解决方案真的很轻松。我只是错过了将工作分配设置为我的数据上下文:

        this.DataContext = workAssignement;

萨拉霍格

相关内容

  • 没有找到相关文章

最新更新