「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

2024.06.09
XML
カテゴリ: WPFC#.NET


WPFで入力値に対して入力規則を設定する方法の1つは、`TextBox` コントロールの `InputBindings` プロパティを使用することです。これにより、ユーザーがテキストボックスに入力する前に、特定のキーの組み合わせやコマンドを処理することができます。


以下のサンプルコードでは、`TextBox` に対して入力規則を設定し、ユーザーが数字のみを入力することを制限します。



<Window x:Class="WpfApp.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="350" Width="525">

    <Grid>

        <TextBox x:Name="textBox" Width="200" Height="30" Margin="10">

            <TextBox.InputBindings>

                <KeyBinding Key="D0" Command="NotACommand" />

                <KeyBinding Key="D1" Command="NotACommand" />

                <KeyBinding Key="D2" Command="NotACommand" />

                <KeyBinding Key="D3" Command="NotACommand" />

                <KeyBinding Key="D4" Command="NotACommand" />

                <KeyBinding Key="D5" Command="NotACommand" />

                <KeyBinding Key="D6" Command="NotACommand" />

                <KeyBinding Key="D7" Command="NotACommand" />

                <KeyBinding Key="D8" Command="NotACommand" />

                <KeyBinding Key="D9" Command="NotACommand" />

                <KeyBinding Key="Back" Command="NotACommand" />

                <KeyBinding Key="Delete" Command="NotACommand" />

                <KeyBinding Key="Left" Command="NotACommand" />

                <KeyBinding Key="Right" Command="NotACommand" />

                <KeyBinding Key="Up" Command="NotACommand" />

                <KeyBinding Key="Down" Command="NotACommand" />

            </TextBox.InputBindings>

        </TextBox>

    </Grid>

</Window>

```


このXAMLでは、`TextBox` に `InputBindings` を設定し、特定のキー(`D0` から `D9` までの数字キー、`Back` キー、`Delete` キー、矢印キー)が入力された場合には何も行わないように `Command="NotACommand"` を指定しています。


こうすることで、ユーザーはテキストボックスに数字以外の文字を入力することができなくなります。しかし、この方法は完全な入力制限ではなく、ユーザーがコピー&ペーストなどで規則に違反するテキストを入力する可能性があります。より厳密な入力規則が必要な場合は、コードビハインドで入力を検証する方法を使用するか、カスタムコントロールを作成して入力制限を行うことが適切です。






お気に入りの記事を「いいね!」で応援しよう

Last updated  2024.06.09 10:34:11


【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! -- / --
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x
X

© Rakuten Group, Inc.
X
Design a Mobile Site
スマートフォン版を閲覧 | PC版を閲覧
Share by: