验证按钮单击事件 wpf c#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14004913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:44:57  来源:igfitidea点击:

validation on button click event wpf c#

wpfvalidationcomboboxtextbox

提问by Sri

I have a WPF application where I have to check a TextBoxvalue and a ComboBox. if it is empty or not on to the format the button click event should fire an error and if the selected index is 0 in the ComboBoxagain it should fire an error.(like in error provider).

我有一个 WPF 应用程序,我必须在其中检查一个TextBox值和一个ComboBox. 如果它为空或不符合格式,则按钮单击事件应触发错误,如果ComboBox再次选择的索引为 0,则应触发错误。(如错误提供程序中)。

I did many research on the internet I came across with the solution with IDataErrorInfo. But the problem is how do i do this on the button click event. All of the examples are doing it on the form load.

我在互联网上做了很多研究,我遇到了IDataErrorInfo的解决方案。但问题是我如何在按钮单击事件上执行此操作。所有的例子都是在表单加载上做的。

I'm quite new for WPF. following is my code

我对 WPF 很陌生。以下是我的代码

public class ClientMap : IDataErrorInfo
{
    public string CDSNo { get; set; }

    public ClientMap(int ID)
    {
        Id = ID;
    }
    public ClientMap()
    {

    }

    public string Error
    {
        get { throw new NotImplementedException(); }
    }

    public string this[string columnName]
    {
        get
        {
            string result = null;
            if (columnName == "CDSNo")
            {
                if (string.IsNullOrEmpty(CDSNo))
                    result = "Please enter a CDS No";
                else
                {
                    string regEx = "[A-Z]{3}-\d{9}-[A-Z]{2}-\d{2}";
                    if (!Regex.IsMatch(CDSNo, regEx))
                    {
                        result = "Invalid CDS No";
                    }
                }
            }

            return result;
        }
    }

    public int Id { get; set; }
    public CE.Data.Customer Customer { get; set; }
    public CE.Data.Institute Institute { get; set; }
    public bool Archived { get; set; }
    public DateTime DateCreated { get; set; }

}

and XAML is

XAML 是

<Window.Resources>
    <validation:ClientMap x:Key="data"/>
</Window.Resources>

<control:AutoCompleteTextBox Style="{StaticResource textBoxInError}">
    <TextBox.Text>
        <Binding Path="CDSNo" Source="{StaticResource data}"
                ValidatesOnDataErrors="True"   
                UpdateSourceTrigger="Explicit">

            <Binding.ValidationRules>
                <ExceptionValidationRule/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</control:AutoCompleteTextBox>

Please help me. Thanks

请帮我。谢谢

回答by Mark Hall

This is modified code from this article. You will need to get the references and additional classes from the download available from that site.

这是本文修改后的代码。您需要从该站点的下载中获取参考资料和其他课程。

Window1.xaml

窗口1.xaml

<Window x:Class="SOTCBindingValidation.Window1" x:Name="This"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SOTCBindingValidation"
    Title="SOTC Validation Test" Height="184" Width="390">
    <Window.Resources>
        <local:ErrorsToMessageConverter x:Key="eToMConverter" />
    </Window.Resources>
    <StackPanel Margin="5">
        <TextBlock Margin="2">Enter An IPv4 Address:</TextBlock>
            <TextBox x:Name="AddressBox">
                <TextBox.Text>
                    <Binding ElementName="This" Path="IPAddress" 
                             UpdateSourceTrigger="Explicit">
                        <Binding.ValidationRules>
                            <local:IPv4ValidationRule />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
        <TextBlock Margin="2" Foreground="Red" FontWeight="Bold" 
            Text="{Binding ElementName=AddressBox, 
                          Path=(Validation.Errors),
                          Converter={StaticResource eToMConverter}}" />
            <Button Name="Btn1" Height ="30" Width="70" Click="Btn1_Click"></Button>
    </StackPanel>

</Window>

Window1.xaml.cs

Window1.xaml.cs

using System.Windows;
using System.Windows.Controls;
namespace SOTCBindingValidation
{

    public partial class Window1 : Window
    {
        public static readonly DependencyProperty IPAddressProperty =
            DependencyProperty.Register("IPAddress", typeof(string),
            typeof(Window1), new UIPropertyMetadata(""));

        public string IPAddress
        {
            get { return (string)GetValue(IPAddressProperty); }
            set { SetValue(IPAddressProperty, value); }
        }

        public Window1()
        { InitializeComponent(); }

        private void Btn1_Click(object sender, RoutedEventArgs e)
        {
            ForceValidation();
            if (!Validation.GetHasError(AddressBox))
            {
                // Put the code you want to execute if the validation succeeds here
            }
        }
        private void ForceValidation()
        {
            AddressBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }

    }
}