かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

わんくまBlogが不安定になったため、前に書いてたはてなダイアリーにメインを移動します。
かずきのBlog@Hatena
技術的なネタは、こちらにも、はてなへのリンクという形で掲載しますが、雑多ネタははてなダイアリーだけに掲載することが多いと思います。
コメント
プログラマ的自己紹介
お気に入りのツール/IDE
プロフィール
経歴
広告
アクセサリ

書庫

日記カテゴリ

[WPF][C#]ついに妥当性検証します! その2

Validationの事に触れたのが半年前。ということで前回のエントリはこちら。
http://blogs.wankuma.com/kazuki/archive/2008/02/11/122718.aspx

今回は、Validationクラスの細かいところをちょっと見てみようと思う。とりあえず復習がてら簡単なValidatorをこさえてみようと思う。前に作ったのと同じ偶数のみOKなバリデータ。さくっと実装。

using System.Windows.Controls;

namespace WpfValidation
{
    /// <summary>
    /// 偶数のみ通すバリデータ
    /// </summary>
    public class MyValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            string inputValue = value as string;
            // 入力は文字列だよね常識的に考えて
            if (value == null)
            {
                return new ValidationResult(false, "おかしい");
            }
            // 数値だよね
            int inputNumber = 0;
            if (!int.TryParse((string)value, out inputNumber))
            {
                return new ValidationResult(false, "数値ではありません");
            }
            // 偶数だよね
            if (inputNumber % 2 != 0)
            {
                return new ValidationResult(false, "偶数ではありません");
            }
            // OK!偶数だ
            return ValidationResult.ValidResult;
        }
    }
}

Window1.xaml.csは、下のような感じ。DataContextの設定と、ボタンが押されたときに、値を表示するだけ。

using System.Windows;

namespace WpfValidation
{
    public partial class Window1 : Window
    {
        // これにテキストボックスの値をバインドする
        public int TargetValue { get; set; }

        public Window1()
        {
            InitializeComponent();
            // お試し用なので、自分自身をDataContextにセット
            this.DataContext = this;
        }

        private void AlertButton_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(this.TargetValue.ToString());
        }
    }
}

XAML側も、前回とほとんど同じなのでさくさくっといくよ。

<Window x:Class="WpfValidation.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WpfValidation="clr-namespace:WpfValidation"
    Title="Validation" Height="99" Width="248">
    <StackPanel>
        <TextBox Margin="3">
            <TextBox.Text>
                <!-- UpdateSourceTriggerをPropertyChangedにしてテキストボックスが
                     変更されたら即ソースを書き換えるようにする。 -->
                <Binding Path="TargetValue" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <!-- 自作のバリデーションルール -->
                        <WpfValidation:MyValidationRule />
                        <!-- 何か例外でたらエラーにしてくれるルール -->
                        <ExceptionValidationRule />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
        <Button Margin="3" Content="Alert" Click="AlertButton_Click" />
    </StackPanel>
</Window>

これで、OK。実行してみよう。偶数以外では、赤枠になってる。
image image image image

Validationプロパティの中身をのぞいてみよう

ということで!バリデーションエラーが起きたときどうなってるのかをちょっと観察してみようと思う。Validation.ErrorsとValidation.HasErrorという添付プロパティがあったりする。その値をAlertを押したときに表示してみようと思う。

まずは、TextBoxにName属性をつけてC#側から触れるようにする。

<TextBox Name="textBox" Margin="3">

次に、AlertのクリックイベントでValidation.ErrorsとValidation.HasErrorを表示するように書き換え。

private void AlertButton_Click(object sender, RoutedEventArgs e)
{
    var hasError = Validation.GetHasError(textBox);
    var errors = Validation.GetErrors(textBox);

    var sb = new StringBuilder();
    // 情報を文字列にして表示
    sb.AppendFormat("Validation.HasError: {0}\n", hasError);
    sb.Append("Validation.Errors: [");
    foreach (var error in errors)
    {
        sb.AppendFormat("{0}, ", error.ErrorContent);
    }
    sb.Append("]");
    MessageBox.Show(sb.ToString());
}

これを実行してみて動きを確認すると、下のような感じになる。
image

実行直後は、エラーも何も無い。奇数を入力してみると…
image

Validation.HasErrorがちゃんとTrueになってValidation.Errorsには、エラーの内容が入っている。エラーがあるときだけ、エラーの内容を表示しようとするとなるとStyleのTriggerを使うと出来る。
要は、TriggerでValidation.HasErrorがTrueのときにToolTipにValidation.Errorsの最初の要素のErrorContentを設定してやればいい。Styleの設定だけ抜粋。

<TextBox.Style>
    <Style TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <!-- エラーがあるときにメッセージをToolTipに表示 -->
            <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>
</TextBox.Style>

本当にやるときには、共通のStyleとしてくくりだすのがいいだろう。実行してみると、エラーメッセージがToolTipとして表示される。すばらしい。
image エラー無し状態

image 数字じゃないとき

image 偶数じゃないとき

投稿日時 : 2008年8月21日 22:19

Feedback

# [C#][Silverlight]Silverlightでの入力値の検証 2008/11/18 23:53 かずきのBlog

[C#][Silverlight]Silverlightでの入力値の検証

# supra uk 2012/12/07 20:54 http://supratkstore.webs.com/

What i do not realize is actually how you're now not really much more neatly-favored than you might be now. You are very intelligent. You already know thus significantly in terms of this subject, made me personally believe it from numerous varied angles. Its like men and women don't seem to be involved until it is one thing to do with Woman gaga! Your individual stuffs excellent. Always take care of it up!

# sacs longchamp 2012/12/14 20:44 http://www.saclongchampachete.info/category/longch

I so want to take an important closer evaluate some of these memorabilia!

# echarpe burberry 2012/12/15 23:01 http://www.sacburberryecharpe.fr/category/foulard-

Thus, our shelves end up filled with stuff that we love.

# sac longchamp 2012/12/16 17:57 http://www.saclongchampachete.info/category/sac-lo

this might be something may very well never possibly read.

# sac longchamp soldes 2012/12/17 2:55 http://www.longchampfr.info/category/sac-longchamp

I definitely like em. It's unlike you dress in these out walking on town persons.

# トリーバーチ 2012/12/17 21:12 http://www.torybruchjp.info/category/トリーバーチ

I am certain that I should visit this place once soon.

# isabel marant bottes 2012/12/18 20:29 http://sneakersisabelmrant-paris.webnode.fr

I waiting to take an important closer look at some of that memorabilia!

# burberry outlet 2012/12/18 20:59 http://www.burberryoutlet2012.info/category/burber

You definitely know an individual's stuff...

# burberry coats 2012/12/19 13:49 http://burberryukoutlets.wordpress.com

If your current photostream features photos in which - regardless of whether good or not - triggered some sort of spirited comments¡ä bond.

# Burberry sortie 2012/12/21 5:27 http://sacburberrysoldesfr.webnode.fr

I understand everybody could hate with them, but I do not think they glance so unhealthy.

# michael kors pas cher 2012/12/22 18:07 http://michael-kors-canada.webnode.fr/news-/

Ill be down again the track to look into other threads that.

# destockprix 2013/03/05 0:39 http://www.f77.fr/

True friendly relationship foresees the requirements of various other in lieu of extol it is really special. destockprix http://www.f77.fr/

# jordan 6 2013/03/05 0:41 http://www.nikerow.com/

Adore stands out as the solely happy and in addition fine solution in your everyday life. jordan 6 http://www.nikerow.com/

# www.jordanretro4air.com 2013/03/05 0:42 http://www.jordanretro4air.com/

Exactly discover married life whilst not having really like, we will see really like whilst not having married life. www.jordanretro4air.com http://www.jordanretro4air.com/

# robenuk site sur 2013/03/05 0:42 http://www.c88.fr/

Not any individual is worth a tears, also , the a person who might be received‘t make you cry out. robenuk site sur http://www.c88.fr/

# c55.fr 2013/03/05 0:43 http://www.c55.fr/

At which there's union with no need of take pleasure in, it will have take pleasure in with no need of union. c55.fr http://www.c55.fr/

# lunettes de vue ray ban 2013/03/05 0:43 http://www.g33.fr/

When it comes to prosperity our new buddys fully understand states; with regard to misfortune children our new buddys. lunettes de vue ray ban http://www.g33.fr/

# code la redoute 2013/03/05 0:43 http://www.k77.fr/

Add‘r waste product your own even on a fella/girlfriend,that isn‘r ready waste product the some time done to you. code la redoute http://www.k77.fr/

# casquette supreme 2013/03/05 0:44 http://www.b66.fr/

Tend not to it's the perfect time who will be confident to get along with. Connect with others who will strength a single prize you and your family moving up. casquette supreme http://www.b66.fr/

# casquette supreme 2013/03/15 5:08 http://www.b44.fr/

That you will find there's partnership and it doesn't involve really enjoy, you might have really enjoy and it doesn't involve partnership. casquette supreme http://www.b44.fr/

# casquette new era 2013/03/16 9:58 http://www.a44.fr/

The case a friendly relationship foresees the requirements of other as compared to promulgate you'll find it's acquire. casquette new era http://www.a44.fr/

# casquette swagg 2013/03/17 10:06 http://www.b77.fr/

An authentic comrade can be a who else overlooks an individual's suprises and even can handle an individual's achievements. casquette swagg http://www.b77.fr/

# destockchine 2013/03/25 5:07 http://c99.fr/

A pal that you simply decide to buy by products will probably purchased in the individual. destockchine http://c99.fr/

# usine23 2013/03/25 5:07 http://e55.fr/

Probably The almighty prefers our business to reach quite a few amiss users ahead of when appointment a good choice, to make certain whenever you at last satisfy the someone, we can recognize how to turn out to be happy. usine23 http://e55.fr/

# coach outlet las vegas 2013/04/06 1:35 http://www.coachoutletcoupon88.com/

May well be Goodness wants states in order to reach a couple different not right everyday people ahead of when interacting with the right one, to make certain that when we finally as a final point fulfill the man or women, in this article discover how to seem glad. coach outlet las vegas http://www.coachoutletcoupon88.com/

# brandalley 2013/04/07 11:59 http://rueree.com/

Peaceful home life happened because of what you are about, yet somehow because of who actually My business is photographs am you've made. brandalley http://rueree.com/

# chaussea 2013/04/08 5:36 http://ruemee.com/

Hardly ever grimace, although the majority of you will be gloomy, to create not know who's plummeting excited about all of your smile. chaussea http://ruemee.com/

# May I simply say what a comfort to find someone that actually understands what they are discussing on the net. You actually understand how to bring an issue to light and make it important. A lot more people have to look at this and understand this side 2018/08/11 3:43 May I simply say what a comfort to find someone th

May I simply say what a comfort to find someone that actually understands
what they are discussing on the net. You actually understand
how to bring an issue to light and make it important.
A lot more people have to look at this and understand
this side of your story. I was surprised you're not more popular given that you surely
possess the gift.

# Excellent article. I certainly love this website. Thanks! 2018/10/04 14:47 Excellent article. I certainly love this website.

Excellent article. I certainly love this website. Thanks!

# You really make it seem so easy with your presentation but I find this matter to be actually something which I think I would never understand. It seems too complex and extremely broad for me. I am looking forward for your next post, I'll try to get the 2018/10/05 2:09 You really make it seem so easy with your presenta

You really make it seem so easy with your presentation but I find this matter to be actually
something which I think I would never understand.
It seems too complex and extremely broad for me.
I am looking forward for your next post, I'll try
to get the hang of it!

# I like the valuable info you provide in your articles. I will bookmark your weblog and check again here frequently. I'm quite certain I will learn many new stuff right here! Best of luck for the next! 2018/10/23 6:03 I like the valuable info you provide in your artic

I like the valuable info you provide in your articles.
I will bookmark your weblog and check again here frequently.

I'm quite certain I will learn many new stuff right here! Best of luck for the next!

# I am sure this article has touched all the internet users, its really really fastidious article on building up new webpage. 2018/10/28 5:00 I am sure this article has touched all the interne

I am sure this article has touched all the internet users, its
really really fastidious article on building up new webpage.

# Howdy! I know this is kind of off topic but I was wondering which blog platform are you using for this site? I'm getting fed up of Wordpress because I've had problems with hackers and I'm looking at alternatives for another platform. I would be awesome 2018/11/10 23:07 Howdy! I know this is kind of off topic but I was

Howdy! I know this is kind of off topic but I was wondering
which blog platform are you using for this site?
I'm getting fed up of Wordpress because I've
had problems with hackers and I'm looking at alternatives for another
platform. I would be awesome if you could point me in the direction of a good platform.

# Hello, just wanted to mention, I enjoyed this post. It was practical. Keep on posting! 2018/11/19 12:54 Hello, just wanted to mention, I enjoyed this post

Hello, just wanted to mention, I enjoyed this post.
It was practical. Keep on posting!

# cjXHqcYoSs 2018/12/17 18:39 https://www.suba.me/

3rzsTe When I look at your website in Ie, it looks fine but when opening in Internet Explorer, it has some overlapping.

# Excellent goods from you, man. I have understand your stuff previous to and you are just too great. I actually like what you have acquired here, really like what you're saying and the way in which you say it. You make it enjoyable and you still take ca 2019/04/07 11:44 Excellent goods from you, man. I have understand y

Excellent goods from you, man. I have understand your stuff previous to and you are just too
great. I actually like what you have acquired here,
really like what you're saying and the way in which you say it.
You make it enjoyable and you still take care of to keep it wise.
I can not wait to read far more from you. This is really
a wonderful web site.

# great issues altogether, you simply gained a emblem new reader. What would you recommend about your submit that you just made some days in the past? Any certain? 2019/05/08 5:42 great issues altogether, you simply gained a emble

great issues altogether, you simply gained a emblem new reader.
What would you recommend about your submit that you just made some days in the past?
Any certain?

# ZzqOZzNLwp 2021/07/03 2:24 https://amzn.to/365xyVY

Thanks-a-mundo for the article.Really looking forward to read more. Much obliged.

# re: [WPF][C#]???????????! ??2 2021/07/18 8:54 can hydroxychloroquine

does chloroquine work https://chloroquineorigin.com/# where do you get hydroxychloroquine

# re: [WPF][C#]???????????! ??2 2021/07/27 19:41 when was hydroxychloroquine first used

is chloroquine phosphate the same as hydroxychloroquine https://chloroquineorigin.com/# how to make hydroxychloroquine

# re: [WPF][C#]???????????! ??2 2021/08/07 5:09 can hydroxychloroquine cause blindness

where to get chloroquine https://chloroquineorigin.com/# where can i get hydroxychloroquine

# Hi, i believe that i noticed you visited my weblog thus i got here to go back the prefer?.I am attempting to to find things to improve my web site!I suppose its adequate to use some of your ideas!! 2021/08/23 21:10 Hi, i believe that i noticed you visited my weblog

Hi, i believe that i noticed you visited my weblog thus
i got here to go back the prefer?.I am attempting to to find
things to improve my web site!I suppose its adequate to use some of
your ideas!!

# Hi, i believe that i noticed you visited my weblog thus i got here to go back the prefer?.I am attempting to to find things to improve my web site!I suppose its adequate to use some of your ideas!! 2021/08/23 21:11 Hi, i believe that i noticed you visited my weblog

Hi, i believe that i noticed you visited my weblog thus
i got here to go back the prefer?.I am attempting to to find
things to improve my web site!I suppose its adequate to use some of
your ideas!!

# Hi, i believe that i noticed you visited my weblog thus i got here to go back the prefer?.I am attempting to to find things to improve my web site!I suppose its adequate to use some of your ideas!! 2021/08/23 21:12 Hi, i believe that i noticed you visited my weblog

Hi, i believe that i noticed you visited my weblog thus
i got here to go back the prefer?.I am attempting to to find
things to improve my web site!I suppose its adequate to use some of
your ideas!!

# Hi, i believe that i noticed you visited my weblog thus i got here to go back the prefer?.I am attempting to to find things to improve my web site!I suppose its adequate to use some of your ideas!! 2021/08/23 21:13 Hi, i believe that i noticed you visited my weblog

Hi, i believe that i noticed you visited my weblog thus
i got here to go back the prefer?.I am attempting to to find
things to improve my web site!I suppose its adequate to use some of
your ideas!!

# Hi there to every body, it's my first visit of this web site; this website includes remarkable and in fact fine material in favor of readers. 2021/08/25 18:03 Hi there to every body, it's my first visit of th

Hi there to every body, it's my first visit of this web site; this website includes remarkable and in fact
fine material in favor of readers.

# Hi there to every body, it's my first visit of this web site; this website includes remarkable and in fact fine material in favor of readers. 2021/08/25 18:04 Hi there to every body, it's my first visit of th

Hi there to every body, it's my first visit of this web site; this website includes remarkable and in fact
fine material in favor of readers.

# This post will help the internet visitors for setting up new website or even a blog from start to end. 2021/09/01 8:34 This post will help the internet visitors for sett

This post will help the internet visitors for setting up new website or even a blog from start to end.

# This post will help the internet visitors for setting up new website or even a blog from start to end. 2021/09/01 8:35 This post will help the internet visitors for sett

This post will help the internet visitors for setting up new website or even a blog from start to end.

# This post will help the internet visitors for setting up new website or even a blog from start to end. 2021/09/01 8:36 This post will help the internet visitors for sett

This post will help the internet visitors for setting up new website or even a blog from start to end.

# This post will help the internet visitors for setting up new website or even a blog from start to end. 2021/09/01 8:37 This post will help the internet visitors for sett

This post will help the internet visitors for setting up new website or even a blog from start to end.

# wemwyimpdyua 2021/11/26 12:50 cegofngv

https://chloroquinephosphates.com/ plaquenil side effects

# Your way of describing the whole thing in this piece of writing is genuinely good, every one can easily be aware of it, Thanks a lot. 2022/03/24 17:28 Your way of describing the whole thing in this pie

Your way of describing the whole thing in this piece of writing is genuinely good, every
one can easily be aware of it, Thanks a lot.

# Your way of describing the whole thing in this piece of writing is genuinely good, every one can easily be aware of it, Thanks a lot. 2022/03/24 17:29 Your way of describing the whole thing in this pie

Your way of describing the whole thing in this piece of writing is genuinely good, every
one can easily be aware of it, Thanks a lot.

# Your way of describing the whole thing in this piece of writing is genuinely good, every one can easily be aware of it, Thanks a lot. 2022/03/24 17:30 Your way of describing the whole thing in this pie

Your way of describing the whole thing in this piece of writing is genuinely good, every
one can easily be aware of it, Thanks a lot.

# Your way of describing the whole thing in this piece of writing is genuinely good, every one can easily be aware of it, Thanks a lot. 2022/03/24 17:31 Your way of describing the whole thing in this pie

Your way of describing the whole thing in this piece of writing is genuinely good, every
one can easily be aware of it, Thanks a lot.

# Wonderful post! We will be linking to this great article on our website. Keep up the great writing. 2022/03/25 2:29 Wonderful post! We will be linking to this great a

Wonderful post! We will be linking to this great
article on our website. Keep up the great writing.

# Wonderful post! We will be linking to this great article on our website. Keep up the great writing. 2022/03/25 2:30 Wonderful post! We will be linking to this great a

Wonderful post! We will be linking to this great
article on our website. Keep up the great writing.

# Wonderful post! We will be linking to this great article on our website. Keep up the great writing. 2022/03/25 2:31 Wonderful post! We will be linking to this great a

Wonderful post! We will be linking to this great
article on our website. Keep up the great writing.

# Wonderful post! We will be linking to this great article on our website. Keep up the great writing. 2022/03/25 2:32 Wonderful post! We will be linking to this great a

Wonderful post! We will be linking to this great
article on our website. Keep up the great writing.

# hepfydnagbaj 2022/05/07 4:22 xyigbm

what is hydroxychloroquine made of https://keys-chloroquineclinique.com/

# joucbajylhjb 2022/05/08 10:31 vmmivz

does hydroxychloroquine have side effects https://keys-chloroquinehydro.com/

# After checking out a handful of the blog articles on your web site, I really like your technique of blogging. I saved as a favorite it to my bookmark website list and will be checking back in the near future. Please visit my website too and let me know 2022/06/04 5:10 After checking out a handful of the blog articles

After checking out a handful of the blog articles on your web site, I really like your technique of blogging.
I saved as a favorite it to my bookmark website list and will be checking back in the near future.

Please visit my website too and let me know what you think.

# Hello, after reading this remarkable article i am too glad to share my know-how here with friends. 2022/06/05 13:32 Hello, after reading this remarkable article i am

Hello, after reading this remarkable article i am too glad to share
my know-how here with friends.

# These are truly fantastic ideas in regarding blogging. You have touched some pleasant factors here. Any way keep up wrinting. 2022/06/07 0:30 These are truly fantastic ideas in regarding blogg

These are truly fantastic ideas in regarding blogging. You
have touched some pleasant factors here. Any way keep
up wrinting.

# Great blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple tweeks would really make my blog stand out. Please let me know where you got your design. Thanks 2022/06/14 17:32 Great blog! Is your theme custom made or did you d

Great blog! Is your theme custom made or did you download it
from somewhere? A theme like yours with a few
simple tweeks would really make my blog stand out. Please let
me know where you got your design. Thanks

# What's up to all, how is everything, I think every one is getting more from this web site, and your views are pleasant for new users. 2022/07/22 23:59 What's up to all, how is everything, I think every

What's up to all, how is everything, I think every one
is getting more from this web site, and your views are pleasant for new users.

# If you desire to get a good deal from this piece of writing then you have to apply such strategies to your won webpage. 2022/08/15 12:17 If you desire to get a good deal from this piece o

If you desire to get a good deal from this piece of writing then you have to apply such
strategies to your won webpage.

# Hey there! This is kind of off topic but I need some help from an established blog. Is it difficult to set up your own blog? I'm not very techincal but I can figure things out pretty quick. I'm thinking about creating my own but I'm not sure where to beg 2022/08/19 15:10 Hey there! This is kind of off topic but I need so

Hey there! This is kind of off topic but I need
some help from an established blog. Is it difficult to set up your own blog?
I'm not very techincal but I can figure things out pretty
quick. I'm thinking about creating my own but
I'm not sure where to begin. Do you have any
tips or suggestions? Cheers

# cheapest plaquenil online 2022/12/25 15:09 MorrisReaks

http://hydroxychloroquinex.com/ generic aralen online

# erectile dysfunction pills https://edpills.science/
best pill for ed 2023/01/07 13:54 EdPills

erectile dysfunction pills https://edpills.science/
best pill for ed

# antibiotic eye drops over the counter https://overthecounter.pro/# 2023/05/08 18:20 OtcJikoliuj

antibiotic eye drops over the counter https://overthecounter.pro/#

タイトル
名前
Url
コメント