WPF从对象绑定到属性

本文关键字:属性 绑定 对象 WPF | 更新日期: 2023-09-27 17:53:54

我将一个属性从一个对象绑定到一个控件,但是这个属性不会更新…

我这样编辑:

ViewModelBase:

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

ViewModel:

public class VIewModel : ViewModelBase
{
    private Person _person;
    public Person Person
    {
        get { return _person; }
        set
        {
            _person = value;
            OnPropertyChanged(nameof(Person));
        }
    }
}

Personclass:

public class Person
{
    public string Name { get; set; }
    public string FirstName { get; set; }
}

App.xamls.cs

protected override void OnStartup(StartupEventArgs e)
{
    var viewModel = new VIewModel
    {
        Person = new Person{FirstName = "Dominik", Name = "Muster"}
    };
    var window = new MainWindow {DataContext = viewModel};
    window.Show();
    base.OnStartup(e);
}

主窗口:

<StackPanel>
    <TextBox Text="{Binding Person.Name}"/>
    <TextBox Text="{Binding Person.FirstName}" Width="200"/>
</StackPanel>

当程序启动时,文本框的值是contact-object的值,但如果我改变文本框中的文本值,属性将不会更新…什么好主意吗?

WPF从对象绑定到属性

尝试在类Person中实现INotifyPropertyChanged:

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _name;
    private string _firstName;
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }

public string FirstName
{
    get
    {
        return _firstName;
    }
    set
    {
        _firstName = value;
        OnPropertyChanged("FirstName");
    }
}
protected void OnPropertyChanged(string name)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(name));
}

}