簡體   English   中英

使用WPF驗證C#中的文本框

[英]Validate textbox in c# with wpf

我有一個帶有一些文本框,combox和復選框的窗口。 文本框之一必須是數字,所以我想對其進行驗證。 我通過互聯網搜索,找到了一個很好的教程 我嘗試使用它,但似乎不起作用,或者我做錯了什么,只是看不到我做錯了什么。 因此,我希望這里的任何人都可以告訴我我做錯了什么,或者是其他解決方案來啟動它。 這是窗口的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");
        }
    }
}

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

您需要為綁定到文本框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..");
        }
    }
}

UpdateSourceTrigger調用此set方法,如果引發異常,則它將在樹中傳播,並且一切都將按預期工作。

希望能幫助到你。

解決我的問題的方法確實很簡單。 我只是想將workassignment設置為我的dataContext:

        this.DataContext = workAssignement;

薩拉若格

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM