0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# / WPFで数字入力欄の値をEnter押下時に指定桁数でゼロ埋めする

Posted at

前説

'0001' のような入力を行うTextBoxで、1を入力すると先頭部分をゼロ埋めするようにしたかった。

こちらの記事を参考に、WPFな業務アプリでキー操作によるフォーカス移動などのビヘイビアを使っていた。
とりえあず↑を参考に動作できたので、忘れないうちにメモ。

ビヘイビアの定義

上記サイトのようにBehaviorsフォルダに以下のようなファイルを追加(元サイトのBehaviorBase.csを継承)。
呼び出すxamlファイルのTextboxに入れる。

TextBoxZeroPadding.cs
using System.Diagnostics;
using System.Windows.Controls;
using System.Windows.Input;

/*
 * XAML内で使うビヘイビア
 *
 * Enter押下時、TextBox内の数字をゼロ埋めする
 *
 */

namespace GyomuApp.Behaviors
{
    /// <summary>
    /// TextBox用ビヘイビア
    /// MaxLengthに沿ってゼロ埋めする
    /// </summary>
    public class TextBoxZeroPadding : BehaviorBase<TextBox>
    {
        /// <summary>
        /// イベント登録
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();

            // TextBoxのキーダウンイベントにOnKeyDownを登録
            AssociatedObject.PreviewKeyDown += OnPreviewKeyDown;
        }

        /// <summary>
        /// イベント解除
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
        }

        /// <summary>
        /// キー押下イベント
        /// </summary>
        /// <param name="sender">TextBox</param>
        /// <param name="e">キーイベントデータ</param>
        private void OnPreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (sender is TextBox textBox)
            {
                switch (e.Key)
                {

                    case Key.Enter:
                        if (textBox.Text == "") break;

                        var zeroForm = new string('0', textBox.MaxLength);
                        var format = "{0:" + zeroForm + "}";

                        textBox.Text = string.Format(format, short.Parse(textBox.Text));

                        break;
                }

            }
        }
    }
}

XAMLファイルは抜粋で書くと↓

                    <!-- 個数 000 -->
                    <TextBox  Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2"
                         HorizontalAlignment="Right" TextWrapping="Wrap" 
                         TextAlignment="Center"
                         FontSize="14"
                         VerticalAlignment="Center" Margin="0,0 0 0" Width="290" 
                         MaxLength="3"
                         Text="{Binding EntryQty, Mode=TwoWay}"
                     >
                        <behaviors:Interaction.Behaviors>
                            <b:TextBoxIntegerOnly />
                            <b:TextBoxMoveFocus />
                            <b:TextBoxZeroPadding /><!-- ← これ -->
                        </behaviors:Interaction.Behaviors>
                    </TextBox>

これで、指定TextBox内で数字を入れてEnterキーをおすと、ゼロ埋めされる。
フォーカス移動のEnterキービヘイビアTextBoxMoveFocusも同時に指定しているが、問題なく動くようだ。

逆に数値入力のみのビヘイビアと同時指定する前提なので、こちらがない場合はエラーが出ると思われる。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?