簡體   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