我是 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());
}
}
}
例如,当我输入 1500TextBox
并键入返回键时,MessageBox
不会反映文本中输入的值。
为什么我的文本框不显示值?