WPF DataBinding从对象的属性

时间:2016-07-01 08:39:44

标签: c# wpf xaml mvvm data-binding

我将属性从对象绑定到控件但属性不会更新...

我试着用这种方式:

ViewModelBase:

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

视图模型:

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的值,但是如果我更改文本框中的文本值,属性将不会更新......任何想法?

1 个答案:

答案 0 :(得分:1)

尝试实现INotifyPropertyChanged在类Person:

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));
}

}