WPF TextBoxへのDoubleのバインド
WPF TextBoxへのDoubleのバインドを行ってみた。
TextBoxにDoubleをバインドしておく。もしエンターキーを押されるとNaNにしてしまう細工を追加。
MainWindow.xaml
<window height="100" mc:ignorable="d" title="MainWindow" width="800" x:class="TextBoxAndDouble.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:TextBoxAndDouble" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <grid> <viewbox> <textbox fontsize="34" keyup="TestKeyUp" text="{Binding Value, Mode=TwoWay, StringFormat=\{0:0.000\}, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=False}" textalignment="Right" textwrapping="Wrap" width="800"> </textbox></viewbox> </grid> </window>
MainWindow.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; 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 TextBoxAndDouble { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); MainWindowsViewModel mainWindowsViewModel = new MainWindowsViewModel(); this.DataContext = mainWindowsViewModel; } private void TestKeyUp(object sender, KeyEventArgs e) { TextBox textBox = (TextBox)sender; if (e.Key == Key.Return) { ((MainWindowsViewModel)this.DataContext).Value = Double.NaN; } } } }
MainWindowsViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; namespace TextBoxAndDouble { class MainWindowsViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } private Double _value = 0.0; public Double Value { set { _value = value; RaisePropertyChanged("Value"); } get { return _value; } } } }