觸發(fā)錯誤處理事件

書名:WPF專業(yè)編程指南
作者:李應(yīng)保
出版社:電子工業(yè)出版社
出版時間:2010-01
ISBN:9787121100116


數(shù)據(jù)綁定

一、在數(shù)據(jù)綁定中加入校驗

4、觸發(fā)錯誤處理事件

  • 要在控件上顯示錯誤信息,別忘了最后一步:在XAML中設(shè)置Binding類中的NotifyOnValidationError屬性,否則,即使校驗有錯,WPF也不會調(diào)用C#中的錯誤處理程序:
            NotifyOnValidationError="true"

下面是完整的主窗口XAML程序:

  <Window
  x:Class="Yingbao.Chapter11.BindingWithBusinessRules.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src=
      "clr-namespace:Yingbao.Chapter11.BindingWithBusinessRules"
    Title="帶校驗的數(shù)據(jù)綁定" Height="150" Width="300">
  <Window.Resources>
    <src:Account  x:Key="MyAccount" TotalAmount="10000.00"/>
  </Window.Resources>
  <Grid DataContext="{StaticResource MyAccount}" >
  <Grid.ColumnDefinitions >
    <ColumnDefinition Width ="120"/>
    <ColumnDefinition Width ="2*"/>
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <RowDefinition  Height ="25" />
    <RowDefinition  Height ="25" />
    <RowDefinition  Height ="25" />
  </Grid.RowDefinitions>
  <Label Content ="用戶賬號:" FontSize ="14" Grid.Row="0"
      Grid.Column ="0"/>
      <TextBox  Name="txtAccount"  HorizontalAlignment ="Center"
      FontSize ="10" Width ="130"
      Height ="18" Grid.Row ="0" Grid.Column ="1">
      <TextBox.Text>
      <Binding Path="AccountNumber"
        NotifyOnValidationError="true">
        <Binding.ValidationRules>
          <src:NumericRule/>
          <src:AccountNumberRule/>
        </Binding.ValidationRules>
      </Binding>
      </TextBox.Text>
    </TextBox>
    <Label Content ="請輸入取款金額:" FontSize ="14" Grid.Row="1"
        Grid.Column ="0"/>
    <TextBox Name="txtWithdraw" HorizontalAlignment ="Center"
        FontSize ="10" Width ="130" Height ="18"  Grid.Row ="1"
        Grid.Column ="1" >
      <TextBox.Text>
      <Binding Path="WithDraw" NotifyOnValidationError="true"
        Mode="OneWayToSource">
          <Binding.ValidationRules>
            <src:WithDrawRule AccountBalance="1000.00"/>
          </Binding.ValidationRules>
      </Binding>
      </TextBox.Text>
    </TextBox>
    <Button Name="btnOK"  Width ="50" Margin ="2" Click="OnOk"
      Grid.Row="2" Grid.Column="1">確認(rèn)</Button>
  </Grid>
  </Window>

相應(yīng)的C#處理程序如下:

  namespace Yingbao.Chapter11.BindingWithBusinessRules
  {
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    public partial class MainWindow: System.Windows.Window
    {
      public MainWindow()
      {
            InitializeComponent();
            Validation.AddErrorHandler(txtAccount, OnAccountError);
            Validation.AddErrorHandler(txtWithdraw,
                        OnWithDrawError);
        }
      void OnAccountError(object sender,
            ValidationErrorEventArgs vea)
      {
            txtAccount.ToolTip = vea.Error.ErrorContent.ToString();
      }
      void OnWithDrawError(object sender,
            ValidationErrorEventArgs vea)
      {
            txtWithdraw.ToolTip = vea.Error.ErrorContent.ToString();
      }
      void OnOk(object sender, EventArgs ea)
      {
            this.Close();
      }
    }
  }

上面的程序在幾種錯誤情況下的運(yùn)行結(jié)果如圖11-5所示。由圖11-5可以看到,當(dāng)出現(xiàn)錯誤時,WPF會自動在控件上加上紅色的邊框,同時Tooltip會顯示出錯信息。


圖11-5 具有校驗功能的數(shù)據(jù)綁定結(jié)果

5、清除控件上的錯誤信息

  • 前面的程序有一個問題,就是在用戶改正了輸入錯誤后,原來的錯誤信息還在相應(yīng)的控件的提示條上。這是因為,當(dāng)校驗正確時我們并沒有清除控件上的控件信息。遺憾的是,ValidationRule里面并沒有通知校驗成功的事件(筆者認(rèn)為應(yīng)該提供),為了清除控件上的錯誤信息,需要用到Validation.Errors這個附加屬性:
  <TextBox.ToolTip>
    <Binding ElementName="txtAccount"
          Path="(Validation.Errors)[0].ErrorContent"/>
  </TextBox.ToolTip>
  • 在上面的XAML語句中,把ToolTip屬性綁定到字符輸入框自己的(Validation.Errors)[0].ErrorContent附加屬性上。也可以不用ElementName,而使用XAML的相對資源擴(kuò)展(RelativeSource),其語法是:
  <TextBox.ToolTip>
      <Binding RelativeSource="{RelativeSource Self}"
        Path="(Validation.Errors)[0].ErrorContent"/>
  </TextBox.ToolTip>

注意:在對ToolTip進(jìn)行上述綁定后,我們就不需要設(shè)置Binding類的NotifyOnValidationError了,也不必在C#中加入事項處理程序。如果不去掉這些代碼,程序仍然可以正確運(yùn)行。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容