0

我是 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不会反映文本中输入的值。

为什么我的文本框不显示值?

4

3 回答 3

0

您需要DataContext在窗口上设置 才能为您完成绑定工作 -

public MainWindow()
{
    InitializeComponent();
    txt.KeyDown += txt_KeyDownHandler;
    myObject = new DataBindingTest();
    DataContext = myObject;
}

有关绑定概述,请参阅此处的此链接。

于 2013-03-23T16:58:37.083 回答
0

除了像 RV1987 写的那样设置 DataContext 之外,您还需要将 UpdateSourceTrigger 设置为 PropertyChanged,因为您不会失去通常会更新源的焦点。

Text="{Binding Path=Montant, UpdateSourceTrigger=PropertyChanged}"
于 2013-03-23T17:01:10.340 回答
0

您需要将 MainWindow 或 masterGrid 的 DataContext 设置为 myObject

于 2013-03-23T17:03:15.690 回答