简体   繁体   English

在MahApps控件中,在加载表单时会触发验证事件,我需要在单击按钮后显示验证消息

[英]In MahApps controls Validation Event raises at the time of form Load I need to show Validation Messages after Button click

IDataErrorInfo: Validating when page submitted IDataErrorInfo:验证何时提交页面

Here I am using IdataErrorInfo 在这里我正在使用IdataErrorInfo

Below is My MainwindowViewModel Class COde 以下是我的MainwindowViewModel类代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using MahApps.Metro;
using MetroDemo.Models;
using System.Windows.Input;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;

namespace MetroDemo
{
    public class AccentColorMenuData
    {
        public string Name { get; set; }
        public Brush BorderColorBrush { get; set; }
        public Brush ColorBrush { get; set; }

        private ICommand changeAccentCommand;

        public ICommand ChangeAccentCommand
        {
            get { return this.changeAccentCommand ?? (changeAccentCommand = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = x => this.DoChangeTheme(x) }); }
        }

        protected virtual void DoChangeTheme(object sender)
        {
            var theme = ThemeManager.DetectAppStyle(Application.Current);
            var accent = ThemeManager.GetAccent(this.Name);
            ThemeManager.ChangeAppStyle(Application.Current, accent, theme.Item1);
        }
    }

    public class AppThemeMenuData : AccentColorMenuData
    {
        protected override void DoChangeTheme(object sender)
        {
            var theme = ThemeManager.DetectAppStyle(Application.Current);
            var appTheme = ThemeManager.GetAppTheme(this.Name);
            ThemeManager.ChangeAppStyle(Application.Current, theme.Item2, appTheme);
        }
    }

    public class MainWindowViewModel : INotifyPropertyChanged, IDataErrorInfo
    {
        private readonly IDialogCoordinator _dialogCoordinator;
        int? _integerGreater10Property;
        int? _emptystring;

        private bool _animateOnPositionChange = true;

        public MainWindowViewModel(IDialogCoordinator dialogCoordinator)
        {
            _dialogCoordinator = dialogCoordinator;
            SampleData.Seed();

            // create accent color menu items for the demo
            this.AccentColors = ThemeManager.Accents
                                            .Select(a => new AccentColorMenuData() { Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush })
                                            .ToList();

            // create metro theme color menu items for the demo
            this.AppThemes = ThemeManager.AppThemes
                                           .Select(a => new AppThemeMenuData() { Name = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush })
                                           .ToList();


            Albums = SampleData.Albums;
            Artists = SampleData.Artists;

            FlipViewTemplateSelector = new RandomDataTemplateSelector();

            FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(Image));
            spFactory.SetBinding(Image.SourceProperty, new System.Windows.Data.Binding("."));
            spFactory.SetValue(Image.HorizontalAlignmentProperty, HorizontalAlignment.Stretch);
            spFactory.SetValue(Image.StretchProperty, Stretch.Fill);
            FlipViewTemplateSelector.TemplateOne = new DataTemplate()
            {
                VisualTree = spFactory
            };
            FlipViewImages = new string[] { "http://trinities.org/blog/wp-content/uploads/red-ball.jpg", "http://savingwithsisters.files.wordpress.com/2012/05/ball.gif" };

            RaisePropertyChanged("FlipViewTemplateSelector");


            BrushResources = FindBrushResources();

            CultureInfos = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures).ToList();
        }

        public string Title { get; set; }
        public int SelectedIndex { get; set; }
        public List<Album> Albums { get; set; }
        public List<Artist> Artists { get; set; }
        public List<AccentColorMenuData> AccentColors { get; set; }
        public List<AppThemeMenuData> AppThemes { get; set; }
        public List<CultureInfo> CultureInfos { get; set; }

        public int? IntegerGreater10Property
        {
            get { return this._integerGreater10Property; }
            set
            {
                if (Equals(value, _integerGreater10Property))
                {
                    return;
                }

                _integerGreater10Property = value;
                RaisePropertyChanged("IntegerGreater10Property");
            }
        }


        public string FirstName { get; set; }
        public string LastName { get; set; }

        DateTime? _datePickerDate;
        public DateTime? DatePickerDate
        {
            get { return this._datePickerDate; }
            set
            {
                if (Equals(value, _datePickerDate))
                {
                    return;
                }

                _datePickerDate = value;
                RaisePropertyChanged("DatePickerDate");
            }
        }







        bool _magicToggleButtonIsChecked = true;
        public bool MagicToggleButtonIsChecked
        {
            get { return this._magicToggleButtonIsChecked; }
            set
            {
                if (Equals(value, _magicToggleButtonIsChecked))
                {
                    return;
                }

                _magicToggleButtonIsChecked = value;
                RaisePropertyChanged("MagicToggleButtonIsChecked");
            }
        }

        private bool _quitConfirmationEnabled;
        public bool QuitConfirmationEnabled
        {
            get { return _quitConfirmationEnabled; }
            set
            {
                if (value.Equals(_quitConfirmationEnabled)) return;
                _quitConfirmationEnabled = value;
                RaisePropertyChanged("QuitConfirmationEnabled");
            }
        }


            }
        }


            }
        }

        public event PropertyChangedEventHandler PropertyChanged;



        /// <summary>
        /// Raises the PropertyChanged event if needed.
        /// </summary>
        /// <param name="propertyName">The name of the property that changed.</param>
        protected virtual void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public string this[string columnName]
        {
            get
            {

                if (columnName == "IntegerGreater10Property" && this.IntegerGreater10Property < 10)
                {
                    return "Number is not greater than 10!";
                }

                if (columnName == "DatePickerDate" && this.DatePickerDate == null)
                {
                    return "No Date given!";
                }

                if (columnName == "FirstName")
                {
                    if (string.IsNullOrEmpty(FirstName) || FirstName.Length < 3)
                        return "Please Enter  First Name";
                }
                if (columnName == "LastName")
                {
                    if (string.IsNullOrEmpty(FirstName) || FirstName.Length < 3)
                        return "Please Enter Last Name";
                }

                return null;
            }
        }

        public string Error { get { return string.Empty; } }

        private ICommand singleCloseTabCommand;

        public ICommand SingleCloseTabCommand
        {
            get
            {
                return this.singleCloseTabCommand ?? (this.singleCloseTabCommand = new SimpleCommand
                {
                    CanExecuteDelegate = x => true,
                    ExecuteDelegate = async x =>
                    {
                        await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("Closing tab!", string.Format("You are now closing the '{0}' tab", x));
                    }
                });
            }
        }

        private ICommand neverCloseTabCommand;

        public ICommand NeverCloseTabCommand
        {
            get { return this.neverCloseTabCommand ?? (this.neverCloseTabCommand = new SimpleCommand { CanExecuteDelegate = x => false }); }
        }


        private ICommand showInputDialogCommand;

        public ICommand ShowInputDialogCommand
        {
            get
            {
                return this.showInputDialogCommand ?? (this.showInputDialogCommand = new SimpleCommand
                {
                    CanExecuteDelegate = x => true,
                    ExecuteDelegate = x =>
                    {
                        _dialogCoordinator.ShowInputAsync(this, "From a VM", "This dialog was shown from a VM, without knowledge of Window").ContinueWith(t => Console.WriteLine(t.Result));
                    }
                });
            }
        }




        private ICommand showProgressDialogCommand;

        public ICommand ShowProgressDialogCommand
        {
            get
            {
                return this.showProgressDialogCommand ?? (this.showProgressDialogCommand = new SimpleCommand
                {
                    CanExecuteDelegate = x => true,
                    ExecuteDelegate = x => RunProgressFromVm()
                });
            }
        }










    }
}

Below is My XAml Code 以下是我的XAml代码

  <TextBox  Name="txt_LA_FirstName"
                         Controls:TextBoxHelper.Watermark="First Name"
                         Controls:TextBoxHelper.UseFloatingWatermark="True"
                         ToolTip="First Name" Grid.Row="2" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Stretch"  Text="{Binding FirstName, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}" />

Event Is Raising at form load and showing Error Messages Before user enters any Value> I need to show Error Messages After Button Click Event 事件在表单加载时引发并显示错误消息,在用户输入任何值之前>我需要在按钮单击事件后显示错误消息

The reason why you get it is because the content of your indexer is static, so the View validates it during the binding. 之所以得到它,是因为索引器的内容是静态的,因此View在绑定期间对其进行了验证。 You should only validate it when the property changes though. 但是,仅应在属性更改时对其进行验证。

You should have a backing field for an errors dictionary with Add/Remove methods, like this 您应该具有使用Add / Remove方法的错误字典的后备字段,例如

    private readonly Dictionary<string, string> errors = new Dictionary<string, string>();
    public string this[string columnName]
    {
        get
        {
            string errorMessage = null;
            if (errors.TryGetValue(columnName, errorMessage) 
            {
                return errorMessage;
            }

            return null;
        }
    }

    protected void AddErrorMessage(string columnName, string errorMessage) 
    {
        errors[columnName] = errorMessage;
    }
    protected void RemoveErrorMessage(string columnName) 
    {
         if(errors.ContainsKey(columnName)) 
        {
            errors.Remove(columnName);
        }
    }

    protected virtual void Validate() 
    {
            errors.Clear();
            if (this.IntegerGreater10Property < 10)
            {
                this.AddErrorMessage("IntegerGreater10Property", "Number is not greater than 10!");
            }

            if (this.DatePickerDate == null)
            {
                this.AddErrorMessage("DatePickerDate", "No Date given!");
            }

            if (string.IsNullOrEmpty(FirstName) || FirstName.Length < 3)
            {
                this.AddErrorMessage("FirstName", "Please Enter  First Name");
            }

            if (string.IsNullOrEmpty(LastName) || Lastname.Length < 3)
            {
                this.AddErrorMessage("LastName", "Please Enter Last Name");
            }
    }

And then remove them with RemoveMessage("FirstName") or clear it up on validation. 然后使用RemoveMessage("FirstName")删除它们,或在验证时将其清除。 You should implement this in a base class of course, to avoid repeating this code over and over again and just override the Validate() method in your ViewModel classes 您当然应该在基类中实现此功能,以避免一遍又一遍地重复此代码,而只需在ViewModel类中重写Validate()方法

Thanks for your reply 感谢您的回复

Even I tried it I had solved it By creating on Bool variable and declaring it as False in MainwindowView model class. 即使我尝试过,也可以通过在Bool变量上创建并在MainwindowView模型类中将其声明为False来解决。

Unless and Until the Bool Variable is True it wont Validates 除非且直到Bool变量为True,否则它不会验证

On Button click Event I will Enable the bool Variable to True then It starts Validates on Button CLick 在按钮上单击事件,我将启用bool变量为True,然后启动按钮CLick上的Validate

if (Enable)
                {



                    if (columnName == "IntegerGreater10Property" && this.IntegerGreater10Property < 10)
                    {
                        return "Number is not greater than 10!";
                    }

                    if (columnName == "DatePickerDate" && this.DatePickerDate == null)
                    {
                        return "No Date given!";
                    }

                    if (columnName == "FirstName")
                    {
                        if (string.IsNullOrEmpty(FirstName) || FirstName.Length < 3)
                            return "Please Enter  First Name";
                    }
                    if (columnName == "LastName")
                    {
                        if (string.IsNullOrEmpty(FirstName) || FirstName.Length < 3)
                            return "Please Enter Last Name";
                    }
                }
                return null;

Below is My Button click Event (On Button I will Enable the Bool Property to true 以下是我的按钮单击事件(在按钮上,我将启用Bool属性为true

 var x = (MainWindowViewModel)DataContext;
            x.Enable = true;

            var binding = txt_LA_FirstName.GetBindingExpression(TextBox.TextProperty);
            binding.UpdateSource();

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

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