繁体   English   中英

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

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

IDataErrorInfo:验证何时提交页面

在这里我正在使用IdataErrorInfo

以下是我的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()
                });
            }
        }










    }
}

以下是我的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}" />

事件在表单加载时引发并显示错误消息,在用户输入任何值之前>我需要在按钮单击事件后显示错误消息

之所以得到它,是因为索引器的内容是静态的,因此View在绑定期间对其进行了验证。 但是,仅应在属性更改时对其进行验证。

您应该具有使用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");
            }
    }

然后使用RemoveMessage("FirstName")删除它们,或在验证时将其清除。 您当然应该在基类中实现此功能,以避免一遍又一遍地重复此代码,而只需在ViewModel类中重写Validate()方法

感谢您的回复

即使我尝试过,也可以通过在Bool变量上创建并在MainwindowView模型类中将其声明为False来解决。

除非且直到Bool变量为True,否则它不会验证

在按钮上单击事件,我将启用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;

以下是我的按钮单击事件(在按钮上,我将启用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