私はWPFが初めてで、テストしたかったDataBinding
ので、以下のコードを書きました:
<Window x:Class="testdatabindingcustomobject.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 x:Name="masterGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="Montant:" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center"/>
<TextBox x:Name="txt" Text="{Binding Path=Montant}" Grid.Column="1" Grid.Row="0" VerticalAlignment="Center" Margin="10,0,0,0"/>
</Grid>
</Window>
そして、C# のコード ビハインドは次のとおりです。
namespace testdatabindingcustomobject
{
public class DataBindingTest : INotifyPropertyChanged
{
double montant;
public event PropertyChangedEventHandler PropertyChanged;
public double Montant
{
get
{return montant;}
set
{
montant = value;
OnPropertyChanged("Montant");
}
}
public DataBindingTest()
{
Montant = 0.000;
}
public void OnPropertyChanged(string mm)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(mm));
}
}
public partial class MainWindow : Window
{
public DataBindingTest myObject;
public MainWindow()
{
InitializeComponent();
txt.KeyDown += txt_KeyDownHandler;
myObject = new DataBindingTest();
}
public void txt_KeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
MessageBox.Show(myObject.Montant.ToString());
}
}
}
たとえば、1500 を入力しTextBox
てリターン キーを入力するとMessageBox
、入力した値がテキストに反映されません。
テキスト ボックスに値が表示されないのはなぜですか?