1. 程式人生 > >WPF Validating事件 替代辦法。

WPF Validating事件 替代辦法。

WPF 在Control控制元件上缺少 Validating事件 及 OnValidating虛擬函式。 需要在使用者焦點 離開頁面時,如果需要執行 “儲存”操作,將會遇到問題。

以下是使用 “事件延遲” 的辦法處理該問題:

IInputElement lastFouces; //一個臨時變數


        protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
        {
            System.Windows.Media.Visual atV = e.NewFocus as System.Windows.Media.Visual;
            if (atV != null && !this.IsAncestorOf(atV))
            {
                lastFouces = e.NewFocus;
                lastFouces.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(NewFocus_GotKeyboardFocus);
            }
            base.OnPreviewLostKeyboardFocus(e);
        }


        void NewFocus_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            ((IInputElement)sender).GotKeyboardFocus -= new KeyboardFocusChangedEventHandler(NewFocus_GotKeyboardFocus);
            ((IInputElement)sender).GotKeyboardFocus -= new KeyboardFocusChangedEventHandler(NewFocus_GotKeyboardFocus);
            string error = CheckAndSavePage();  //  執行功能函式,返回錯誤資訊。
            if (!string.IsNullOrEmpty(error))
            {
                MessageBoxResult aMR = MessageBox.Show(error + "\r\n是否繼續?\r\n點選“是”放棄修改,點選“否”繼續編輯。", "輸入錯誤", MessageBoxButton.YesNo, MessageBoxImage.Error);
                if (aMR == MessageBoxResult.Yes)
                {
                    this.RefreshData(); // 重新整理頁面,重新繫結
                }
                else
                {
                    this.dgAra.Focus(); //繼續停留在本頁面, 如果lastFouces有焦點相關的事件處理函式,可能會出錯。
                    return;
                }
            }
            else
            {
                this.RefreshData();
            }
        }