Zhou's profileSheva's TechSpacePhotosBlogLists Tools Help

Blog


    11/25/2007

    DataErrorValidationRule - New Way To Invalidate Data In WPF

    The WPF 3.5 has introduced a new data validation API aka DataErrorValidationRule, which you can specify on the Binding object, if the data source implements the IDataErrorInfo interface. This new feature enables some of the scenario the previous Custom ValidationRule cannot enable.

    One of the scenario the custom ValidationRule cannot support is to enable data binding on the properties of the Custom ValidationRule class. Because ValidationRule is not a DependencyOject, you cannot define dependency properties on it to enable data binding. And because ValidationRule is not a part of the element tree, any Binding expression which relies on RelativeSource or ElementName or similar things that needs to walk up the element tree to find the binding source cannot be evaluated successfully. Some community members such as Josh Smith has come up with a hackery to workaround this limitation using the trick he calls "Virutal Branches". Or our beloved Dr. WPF's ObjectReference custom Markup Extension as he "bloated" in this MSDN WPF thread.

    DataErrorValidationRule drives those "dirty tricks" to obsolete. Because You don't need to bind some values to custom ValidationRule object as validation input parameters. Because when implementing IDataErrorInfo, you do the validation logic at the source object. The following is an example of how to leverage the DataErrorValidationRule API to suppport the type of scenario "Virtual Branches" is trying to enable.

    First off, the data source class should implement IDataErrorInfo or INotifyPropertyChanged if you want to enable two way data binding as follows:

    public class Person : IDataErrorInfo, INotifyPropertyChanged
    {
        private int age;
        private int min = 0;
        private int max = 150;

        public int Age
        {
            get { return age; }
            set
            {
                age = value;
                RaisePropertyChanged("Age");
            }
        }

        public string Error
        {
            get
            {
                return null;
            }
        }

        public int Min
        {
            get
            {
                return min;
            }
            set
            {
                min = value;
                RaisePropertyChanged("Min");
            }
        }

        public int Max
        {
            get
            {
                return max;
            }
            set
            {
                max = value;
                RaisePropertyChanged("Max");
            }
        }

        public string this[string name]
        {
            get
            {
                string result = null;

                if (name == "Age")
                {
                    if (this.age < this.Min || this.age > this.Max)
                    {
                        result = String.Format("Age must not be less than {0} or greater than {1}.", this.Min, this.Max);
                    }
                }
                return result;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

    You can see that Min and Max properties needs to be specified by the user, so we need to bind those two properties to corresponding UI elements as following XAML snippet shows:

    <Window x:Class="BusinessLayerValidation.Window1"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           Title="WPF IDataErrorInfo Sample"
           Width="450" Height="170"
           xmlns:src="clr-namespace:BusinessLayerValidation">

      <
    Window.Resources>
        <
    src:Person x:Key="data"/>
        <
    Style x:Key="textBoxInError" TargetType="TextBox">
          <
    Style.Triggers>
            <
    Trigger Property="Validation.HasError" Value="true">
              <
    Setter Property="ToolTip"
                     Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                            Path=(Validation.Errors)[0].ErrorContent}
    "/>
            </
    Trigger>
          </
    Style.Triggers>
        </
    Style>
      </
    Window.Resources>

      <
    StackPanel Margin="20" DataContext="{Binding Source={StaticResource data}}">
        <
    StackPanel Orientation="Horizontal">
          <
    TextBlock Width="60">
            Min:(<TextBlock Text="{Binding Path=Value, ElementName=minSlider}"/>)
          </TextBlock>
          <
    Slider Margin="10, 0, 0, 0"
                  Name="minSlider"
                  Width="300"
                  Orientation="Horizontal"
                  IsSnapToTickEnabled="True"
                  HorizontalAlignment="Right"
                  TickPlacement="BottomRight"
                  AutoToolTipPlacement="BottomRight"
                  Value="{Binding Path=Min, Mode=TwoWay}"
                  Minimum="0"
                  Maximum="150"
                  TickFrequency="10"/>
        </
    StackPanel>
        <
    StackPanel Orientation="Horizontal">
          <
    TextBlock Width="60">
            Max:(<TextBlock Text="{Binding Path=Value, ElementName=maxSlider}"/>)
          </TextBlock>
          <
    Slider Margin="10, 0, 0, 0"
                  Name="maxSlider"
                  Width="300"
                  Orientation="Horizontal"
                  IsSnapToTickEnabled="True"
                  HorizontalAlignment="Right"
                  TickPlacement="BottomRight"
                  AutoToolTipPlacement="BottomRight"
                  Value="{Binding Path=Max, Mode=TwoWay}"
                  Minimum="0"
                  Maximum="150"
                  TickFrequency="10"/>
        </
    StackPanel>
        <
    TextBlock>Enter your age:</TextBlock>
        <
    TextBox Style="{StaticResource textBoxInError}" Name="textBox">
          <
    TextBox.Text>
            <
    Binding Path="Age"
                    ValidatesOnDataErrors="True"
                    UpdateSourceTrigger="PropertyChanged">
              <
    Binding.ValidationRules>
                <
    ExceptionValidationRule/>
              </
    Binding.ValidationRules>
            </
    Binding>
          </
    TextBox.Text>
        </
    TextBox>
      </
    StackPanel>
    </
    Window>

    You can see from the XAML shown above that DataErrorValidationRule actually provide a greater flexibility when validating data. For a detailed introduction to DataErrorValidationRule, and its role in the WPF data validation model, you can refer to this WPF SDK blog article.

    For completeness, I've attached full sample project here for further reference.

    Attachment: WPFDataValidation.zip

    Comments (37)

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.
    Zhou Yong has turned off comments on this page.
    No namewrote:
    Today, the Microsoft-owned in-game ad agency said that it has signed an exclusive multiyear agreement with Blizzard. Azerothians opposed to seeing in-game ads in their local <P><A href="http://www.game4power.com/">world of warcft gold</A></P> watering holes need not worry, however, because the deal is limited to Blizzard's Web sites and Battle.net,the game maker's online-gaming hub. Terms of the deal were not announced, but Massive did note that the agreement is applicable to users in the US, Canada, Europe, South Korea, and Australia.
    <P><A href="http://www.game4power.com/">buy wow gold</A></P>


    Massive also said today that it would be extending its aforementioned deal with Activision to encompass an additional 18 games appearing on the Xbox 360 and PC.<P><A href="http://www.wowgoldone.com/">cheap wow gold</A></P>The agency didn't fully delineate which would fall under this deal, though it did call out Guitar Hero: World Tour, James Bond: Quantum of Solace, and Transformers: Revenge of the Fallen,<P><A href="http://www.itemstores.com/">buy wow items</A></P> as well as games in its Tony Hawk and AMAX Racing franchises.Shortly before Activision and Vivendi announced their deal of the decade,<P><A href="http://www.gamelevelup.com/">wow power leveling</A></P> the Guitar Hero publisher signed on to receive in-game advertisements from Massive Inc for a number of its Xbox 360 and PC games. A bit more than a year later, Massive is now extending its reach to Activision's new power player, Blizzard Entertainment.<P><A href="http://www.game4power.com/">buy wow gold</A></P> from our site ,you'll get more surprises!
    Dec. 26
    No namewrote:
    割り切り http://warikiri.inu01.com
    即ハメ http://sokuhame.inu01.com
    過激 http://kageki.inu01.com
    露出 http://rosyutu.inu01.com
    変態 http://hentai.inu01.com
    スワッピング http://suwappingu.inu01.com
    未亡人 http://miboujin.inu01.com
    初体験 http://hatutaiken.inu01.com
    女調教 http://onnatyoukyou.inu01.com
    S女 http://esuonna.inu01.com
    女教師 http://jokyoushi.inu01.com
    人妻出会い http://hitodumadeai.inu01.com
    野外露出 http://yagairoshutu.inu01.com
    痴女 http://tijo.inu01.com
    乱交 http://rankou.inu01.com
    いい女 http://iionna.inu01.com
    素人無料 http://siroutomuryou.inu01.com
    素人娘 http://siroutomusume.inu01.com
    綺麗なお姉さん http://kireinaoneesan.inu01.com
    かわいい女の子 http://kawaiionnanoko.inu01.com
    女子大生 http://joshidaisei.inu01.com
    制服 http://seihuku.inu01.com
    ぎゃる http://gal.inu01.com
    メイド http://meido.inu01.com
    ぽっちゃり http://pottyari.inu01.com
    ナンパ http://nanpa.inu01.com
    スケベ http://sukebe.inu01.com
    エロ女 http://eroonna.inu01.com
    エロカワ http://erokawa.inu01.com
    淫乱女 http://inranonna.inu01.com
    スッチー http://suttii.inu01.com
    キャバ嬢 http://kyabajou.inu01.com
    お姉さん http://oneesan.inu01.com
    美人 http://bijin.inu01.com
    独身 http://dokushin.inu01.com
    出会う http://deau.inu01.com
    即会い http://sokuai.inu01.com
    会いたい http://aitai.inu01.com
    交際クラブ http://kousaiclub.inu01.com
    出会無料 http://deaimuryou2.inu01.com
    無料出会 http://muryoudeai.inu01.com
    出会 http://deai.inu01.com
    メル友掲示板 http://merutomokeijiban.inu01.com
    メルトモ http://merutomo.inu01.com
    出会系 http://deaikei.inu01.com
    彼氏募集 http://kareshibosyuu.inu01.com
    女の子 http://onnanoko.inu01.com
    彼女欲しい http://karesihosii.inu01.com
    彼女 http://kanojyo.inu01.com
    清純 http://seijun.inu01.com
    Dec. 15
    No namewrote:
    彼氏 http://karesi.ep15.net
    男性 http://dansei.ep15.net
    男の子 http://otokonoko.ep15.net
    イケメン http://ikemen.ep15.net
    男らしい http://otokorasii.ep15.net
    メール http://mailkara.ep15.net
    美少年 http://bisyounen.ep15.net
    メル友 http://merutomo.ep15.net
    友達 http://tomodachi.ep15.net
    パートナー http://partner.ep15.net
    運命の人 http://unmeinohito.ep15.net
    王子様 http://ohjisama.ep15.net
    真面目 http://majime.ep15.net
    ダーリン http://darlin.ep15.net
    美男子 http://bidanshi.ep15.net
    セックスフレンド http://sexfrend.ep15.net
    sex http://sex.ep15.net
    ヤリ友 http://yaritomo.ep15.net
    H http://h.ep15.net
    セフレ http://sefure.ep15.net
    愛人 http://aijin.ep15.net
    えっち http://etti.ep15.net
    出会いサイト http://deaisite.ep15.net
    出会い系 http://deaikei.ep15.net
    出会い系サイト http://deaikeisite.ep15.net
    浮気 http://uwaki.ep15.net
    不倫 http://furin.ep15.net
    大人の関係 http://otonanokankei.ep15.net
    援助交際 http://enjyokousai.ep15.net
    性処理 http://seisyori.ep15.net
    彼氏欲しい http://kareshihosii.inu01.com
    出会い無料サイト http://deaimuryuousite.inu01.com
    寂しい http://samisii.inu01.com
    異性 http://isei.inu01.com
    出会い無料 http://deaimuryou.inu01.com
    メールフレンド http://mailfrend.inu01.com
    純粋 http://junsui.inu01.com
    交際 http://kousai.inu01.com
    メール友達 http://mailtomodati.inu01.com
    無料メル友 http://muryoumerutomo.inu01.com
    出会い掲示板 http://deaikeijiban.inu01.com
    無料出会い系 http://muryoudeaikei.inu01.com
    優良出会い http://yuuryoudeai.inu01.com
    出会いたい http://deaitai.inu01.com
    完全無料出会い http://kanzenmuryoudeai.inu01.com
    結婚相手 http://kekkonaite.inu01.com
    結婚したい http://kekkonsitai.inu01.com
    恋愛結婚 http://renaikekkon.inu01.com
    恋愛 http://renai.inu01.com
    幸せ http://shiawase.inu01.com
    Dec. 15
    Dec. 12
    Nov. 27
    No namewrote:
    労働問題 収益物件不動産売却などにはマンション査定土地売買1戸建て売却が含まれる賃貸 住宅不動産 賃貸賃貸マンション新築マンションもしっかりカバーしてありすごく充実したさいとでもちろん投資を目的の方やリフォームをしたい人もすごく参考になるだう。ところで今,SEO対策などいまはやっているがホームページ制作会社にいらいしてもうまくはいかないようだ。最近私は、資産運用にこっていて税金対策にインテリアを集めている。もちろんファッションにこだわりブランド品や下着,ランジェリーにはこだわりがある。 化粧品ダイエット用品高価なものがよく家具も最高級しか買わない、先日海外旅行にいってきてお土産に外車結婚指輪と高級時計をかったが、日本でしらべたら通販ですごく安く売っていた。 物件探しは広島 不動産 岡山 不動産 松山市 不動産 香川県 不動産 徳島 不動産 高知 不動産 高松 不動産をフルカバーしてます大手で 和歌山 富山 滋賀 石川 山梨 新潟 沖縄 大分 鹿児島 宮崎 熊本 高知
    Nov. 20
    Nov. 20
    Nov. 8
    Nov. 8
    No namewrote:

    Hi,Do you have used LCDs, second hand LCDs, used flat screens and used LCD monitors? Please go here:www.sstar-hk.com(Southern Stars).We are constantly buying re-usable LCD panels and working for LCD recycling.The re-usable panels go through strictly designed process of categorizing, checking, testing, repairing and refurbishing before they are re-used to make remanufactured LCD displays and TV sets.Due to our recent breakthrough in testing and repairing technology of LCD, we can improve the value for your LCD panels. website:www.sstar-hk.com[dajggcifhfbagaf]

    Oct. 26
    Oct. 17
    No namewrote:
    HTML clipboard情趣用品,情趣用品,情趣用品,情趣用品,情趣,情趣,情趣,情趣,按摩棒,震動按摩棒,微調按摩棒,情趣按摩棒,逼真按摩棒,G點,跳蛋,跳蛋,跳蛋,性感內衣,飛機杯,充氣娃娃,情趣娃娃,角色扮演,性感睡衣,SM,潤滑液,威而柔,香水,精油,芳香精油,自慰套,自慰,性感吊帶襪,吊帶襪,情趣用品加盟AIO交友愛情館,情人歡愉用品,美女視訊,情色交友,視訊交友,辣妹視訊,美女交友,嘟嘟成人網,成人網站,A片,A片下載,免費A片,免費A片下載情人歡愉用品,情趣用品,成人網站,情人節禮物,情人節,AIO交友愛情館,情色,情色貼圖,情色文學,情色交友,色情聊天室,色情小說,七夕情人節,色情,情色電影,色情網站,辣妹視訊,視訊聊天室,情色視訊,免費視訊聊天,美女視訊,視訊美女,美女交友,美女,情色交友,成人交友,自拍,本土自拍,情人視訊網,視訊交友90739,生日禮物,情色論壇,正妹牆,免費A片下載,AV女優,成人影片,色情A片,成人論壇,情趣,情境坊歡愉用品,免費成人影片,成人電影,成人影城,愛情公寓,成人影片,保險套,舊情人,微風成人,成人,成人遊戲,成人光碟,色情遊戲,跳蛋,按摩棒,一夜情,男同志聊天室,肛交,口交,性交,援交,免費視訊交友,視訊交友,一葉情貼圖片區,性愛,視訊,視訊聊天,A片,A片下載,免費A片,嘟嘟成人網,寄情築園小遊戲,女同志聊天室,免費視訊聊天室,一夜情聊天室,聊天室愛情公寓,情色,舊情人,情色貼圖,情色文學,情色交友,色情聊天室,色情小說,一葉情貼圖片區,情色小說,色情,色情遊戲,情色視訊,情色電影,aio交友愛情館,色情a片,一夜情,辣妹視訊,視訊聊天室,免費視訊聊天,免費視訊,視訊,視訊美女,美女視訊,視訊交友,視訊聊天,免費視訊聊天室,情人視訊網,影音視訊聊天室,視訊交友90739,成人影片,成人交友,美女交友,微風成人,嘟嘟成人網,成人貼圖,成人電影,A片,豆豆聊天室,聊天室,UT聊天室,尋夢園聊天室,男同志聊天室,UT男同志聊天室,聊天室尋夢園,080聊天室,080苗栗人聊天室,6K聊天室,女同志聊天室,小高聊天室,上班族聊天室,080中部人聊天室,同志聊天室,聊天室交友,中部人聊天室,成人聊天室,一夜情聊天室,情色聊天室,寄情築園小遊戲
    Oct. 14
    Sept. 30
    Sept. 25
    Sept. 25
    Picture of Anonymous
    UII wrote:

    盲導犬は盲目の人の歩行補助に犬が使われた例、盲目の乞食や辻音楽師が犬に引かれて歩く姿は色々な絵に描かれており、盲導犬その最も古い例はポンペンの発掘品の中に見られ、13世紀の中国の絵などその後数世紀にわたって同じような絵が発見されているが、盲導犬それらはどれも長いロープで繋がれた犬が、視覚障害者を引っ張っている、というものばかりであった。盲導犬確実な資料では、1819年、ヨハン. ウイルヘルム・クラインというウイーンの神父が、盲導犬犬の首輪に細長い棒をつけとして正式に訓練したのが最初である。その後1916年に、ドイツ赤十字のシュターリンとドイツシェパード犬協会のシュテファニッツが、第一世界大戦中、戦盲者のために盲導犬を育成しようとオルテブルグに学校を設立し、翌年にが作出されて戦盲者の誘導に役立てた。1923年にはポツダムに国立の盲導犬学校が設立され、多数のが誕生し戦盲者の社会復帰を促した。

     

    Sept. 25
    Picture of Anonymous
    yKO wrote:

    東京 一戸建て購入なら首都圏の・東京 一戸建て・分譲一戸建て一戸建てを自分で「選ぶ」「 くらべる」ホームプラザ。東京 一戸建て情報をはじめ住宅・不動産物件購入に役立つ情報満載です。住友不動産販売(住友の仲介)では、マンション、東京 一戸建て、土地などの不動産物件の最新情報から、不動産の取引のお手伝い、その際に必要となる知識や知っておきたい関連情報など、不動産に関する様々な情報を掲載しております。関東エリアの東京 一戸建てを、エリアやその他さまざまな詳細条件で探せます。

    Sept. 25
    Picture of Anonymous
    U8 wrote:

    当サイトお見合いパーティー『お見合いパーティーに行こう!』は独身の方達のために、今では出会いのきっかけの場として市民権を得ているお見合いパーティーで意中の相手を獲得して 幸せになるための情報を提供するお見合いパーティー総合情報サイトです。お見合いパーティー『お見合いパーティーは全国各地で開催されていますが、当サイトではみなさんからの要望の高い札幌、東京、横浜、名古屋、京都、大阪、福岡だけはお見合いパーティー重点的にスポットを当ててみました。当サイトがきっかけとなり一人でも多くの良い出会いが生まれれば嬉しいなと思っています。どうぞごゆっくりご覧下さい。

    Sept. 25
    Sept. 6
    Sept. 6

    Trackbacks

    The trackback URL for this entry is:
    http://shevaspace.spaces.live.com/blog/cns!FD9A0F1F8DD06954!639.trak
    Weblogs that reference this entry
    • None