简体   繁体   English

WPF文本框绑定

[英]WPF TextBox Bind

I have a class called VoucherEntity, includes a Property named "Customer", a object of Class CustomerEntity, so I have bellow code, 我有一个名为VoucherEntity的类,其中包含一个名为“ Customer”的属性,它是Class CustomerEntity的对象,因此我有下面的代码,

<TextBox Height="23" IsReadOnly="False" HorizontalAlignment="Stretch" Margin="124,48,174,0" Name="txt_customer" VerticalAlignment="Top" Text="{Binding Path=Customer.Name}" />

in .cs file, I have bellow code 在.cs文件中,我有以下代码

_voucher = new VoucherEntity();
this.DataContext = _voucher;

it means, at first, the Customer property is null, after clicked a button, I will give Customer property of _voucher a CustomerEntity object, then I hope the TextBox can display it immediately, but failed, what should I do? 这意味着,首先,Customer属性为null,单击按钮后,我将给_voucher的Customer属性一个CustomerEntity对象,然后希望TextBox可以立即显示它,但失败了,我该怎么办?

If you want to except changes in your view you should notify the view about the changes. 如果要在视图中排除更改,则应将更改通知给视图。

So just implement the INotifyPropertyChanged interface in the VoucherEntity class and fire the PropertyChanged event after you set the Customer prop 因此,只需在VoucherEntity类中实现INotifyPropertyChanged接口,并在设置Customer PropertyChanged之后触发PropertyChanged事件

public class VoucherEntity: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void FirePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    private CustomerEntity _customer;
    public CustomerEntity Customer
    {
        get {return _customer;}
        set
        {
            if (_customer != value)
            {
                _customer= value;
                FirePropertyChanged("Customer");
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM