WPFでTextBoxに数値をバインドしている場合に入力範囲に制限を設ける例を探していた。
概要としてはEnterキーを押すと入力のチェックが始まり範囲内なら入力が新しい変数値として適用されて,出力側もPropertyChangedイベンドをきっかけに変更される。
MainWindows.xaml
<Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" mc:Ignorable="d" Title="MainWindow" Height="100" Width="300"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <TextBlock Grid.Column="0" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center">入力</TextBlock> <TextBlock Grid.Column="0" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">出力</TextBlock> <TextBox Grid.Column="1" Grid.Row="0" Width="70" VerticalAlignment="Center" HorizontalAlignment="Center" TextAlignment="Right" KeyUp="OnKeyUp"> <TextBox.Text> <Binding Path="Value" Mode="TwoWay" UpdateSourceTrigger="LostFocus"> <Binding.ValidationRules> <local:DoubleRangeRule MinValue="0" MaxValue="100" /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> <TextBox Text="{Binding Value, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1" Grid.Row="1" Width="70" Foreground="SkyBlue" Background="AliceBlue" IsReadOnly="True" VerticalAlignment="Center" HorizontalAlignment="Center" TextAlignment="Right"/> </Grid> </Window>
MainWindows.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApp1 { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { private MainWindowViewModel mainWindowViewModel; public MainWindow() { InitializeComponent(); mainWindowViewModel = new MainWindowViewModel(); this.DataContext = mainWindowViewModel; } private void OnKeyUp(object sender, KeyEventArgs e) { TextBox textBox = (TextBox)sender; if (e.Key == Key.Return) { //System.Windows.Input.Keyboard.ClearFocus(); textBox.RaiseEvent(new RoutedEventArgs(LostFocusEvent, textBox)); } } } }
DoubleRangeRule.cs
(参考ページのintを全部doubleに変更するだけ。) ちなみに以下は必要 using System.Windows.Controls; using System.Globalization;