酢ろぐ!

カレーが嫌いなスマートフォンアプリプログラマのブログ。

Windows PhoneでTextBoxの入力値チェックを行う

Windows PhoneでのTextBoxなどに入力された文字列(入力値のチェック)はどうしましょう?

よくあるケースとしては、メールアドレスの入力で「@」が入力が抜けているケースです。

TextBoxの枠を赤くしてユーザーへ入力値に誤りがあることを通知したいと考えます。説明を簡単にするために入力されたテキストの文字数が3文字以下ならエラーとして、4文字以上ならエラーとして扱います。

f:id:ch3cooh393:20141225191058p:plain

入力値の検証の事をValidation(バリデーション)といいます。

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" DataContext="{Binding}">
    <TextBox Name="textMessage" BindingValidationError="textMessage_BindingValidationError" 
             Height="73" HorizontalAlignment="Left" Margin="24,31,0,0" VerticalAlignment="Top" Width="412" >
        <TextBox.Text>
            <Binding Path="TextMessage" Mode="TwoWay" NotifyOnValidationError="True" ValidatesOnExceptions="True"/>
        </TextBox.Text>
    </TextBox>
    <Button Name="btnSend" Content="Send" IsEnabled="False" 
            Height="72" HorizontalAlignment="Left" 
            Margin="290,100,0,0" VerticalAlignment="Top" Width="160" />
</Grid>

データバインディングするViewModelを定義しましょう。

public class TextViewModel : INotifyPropertyChanged {
    private string _textMessage;
    public string TextMessage {
        get { return _textMessage; }
        set {
            if (value != _textMessage) {

                if (value.Length < 4) {
                    throw new ArgumentException("3文字以下はダメ");
                }

                _textMessage = value;
                NotifyPropertyChanged("TextMessage");
            }
        }
    }

   #region INotifyPropertyChanged関係
    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName) {
        if (PropertyChanged != null) {
            PropertyChanged(this, 
                new PropertyChangedEventArgs(propertyName));
        }
    }
   #endregion
}

Page側でBindingValidationErrorを受け取るようにします。

public partial class MainPage : PhoneApplicationPage {
    // Constructor
    public MainPage() {
        InitializeComponent();
        DataContext = new TextViewModel();
    }

    private void textMessage_BindingValidationError(object sender, ValidationErrorEventArgs e) {
        
        e.Handled = true;  
        var textBox = (TextBox)e.OriginalSource;

        switch (e.Action) {
            case ValidationErrorEventAction.Added:
                // 入力値エラー(バリデーションエラー)が発生したとき
                textMessage.BorderBrush = new SolidColorBrush(Colors.Red);
                btnSend.IsEnabled = false;
                break;
            case ValidationErrorEventAction.Removed:
                // 入力値エラー(バリデーションエラー)が除外できた
                textMessage.BorderBrush = new SolidColorBrush(Colors.Transparent);
                btnSend.IsEnabled = true;
                break;
        }
    }
}

f:id:ch3cooh393:20141225191120p:plain

オンブラウザなSilverlightの場合、ToolTipService.SetToolTipメソッドでツールチップ(吹き出し)を表示したり出来るみたいなのですが、