需要帮助才能进行简单的文本框验证

时间:2016-04-18 12:13:00

标签: c# wpf validation

我是wpf的新手,我尝试了很多教程,使用ValidationRule轻松验证,但没有什么可以帮助我,我很困惑! 我的问题是实现我自己的项目 我点击按钮时有一个主窗口显示一个要求输入数字的对话框,我需要对这个号码进行验证

这是对话框的XAML:

<Window x:Name="kInputWindow1" x:Class="FinalProject.kInputWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:FinalProject"
     Title="Input" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen"
    ContentRendered="Window_ContentRendered">
<Grid Margin="15">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <Image Source="question.jpg" Width="32" Height="32" Grid.RowSpan="2" Margin="20,0" />

    <Label Name="lblQuestion" Grid.Column="1">Question:</Label>
    <TextBox Name="txtAnswer" MinWidth="250" Grid.ColumnSpan="2" Margin="71,26,0.6,0" Grid.RowSpan="2" PreviewTextInput="NumberValidationTextBox" 
             ToolTip="{Binding RelativeSource={RelativeSource Self},  Path=(Validation.Errors)[0].ErrorContent}">
        <TextBox.Text>
            <Binding Path="txtAnswer" UpdateSourceTrigger="PropertyChanged" 
                 ValidatesOnDataErrors="True" ValidatesOnExceptions="True">
                <Binding.ValidationRules>
                    <DataErrorValidationRule />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

    <WrapPanel Grid.Row="2" Grid.ColumnSpan="2" HorizontalAlignment="Right" Margin="0,15,0,0">
        <Button IsDefault="True" Name="btnDialogOk" Click="btnDialogOk_Click" MinWidth="60" Margin="0,0,10,0">_Ok</Button>
        <Button IsCancel="True" MinWidth="60">_Cancel</Button>
    </WrapPanel>
</Grid>

这是代码:

public partial class kInputWindow : Window
{

    public kInputWindow(string question)
    {
        InitializeComponent();
        lblQuestion.Content = question;
    }

    private void btnDialogOk_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = true;
    }

    private void Window_ContentRendered(object sender, EventArgs e)
    {
        txtAnswer.SelectAll();
        txtAnswer.Focus();
    }

    public string Answer
    {
        get { return txtAnswer.Text; }
    }

    private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
    {
        Regex regex = new Regex("[^0-9]+");
        e.Handled = regex.IsMatch(e.Text);
    }

}

public class CustomValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (string.IsNullOrEmpty(value.ToString()))
            return new ValidationResult(false, "No number was entered!");
        if (value.ToString().Contains(' '))
            return new ValidationResult(false, "No spaces allowed!");

        return ValidationResult.ValidResult;
    }
}

我真的不知道为了让它的工作缺少什么

1 个答案:

答案 0 :(得分:0)

您的代码中有2个错误: 1.您使用DataErrorValidationRule而不是您自己的CustomValidationRule。所以应该是这样的:

<Binding.ValidationRules>
  <local:CustomValidationRule/>
</Binding.ValidationRules>

2。您需要在“文本绑定”属性上具有正确的路径。现在你绑定了属性“txtAnswer”但是你的TextBox.DataContext中没有这样的属性(实际上你根本就没有DataContext)。使其工作的最小示例是将示例属性添加到Window并将Window设置为自身的DataContext:

public partial class kInputWindow  : Window
{
  public string ResultText { get; set; }

  public MainWindow()
  {
    InitializeComponent();
    this.DataContext = this;
   }

然后将TextBox绑定到此属性:

<Binding Path="ResultText" UpdateSourceTrigger="PropertyChanged" 
             ValidatesOnDataErrors="True" ValidatesOnExceptions="True">