将TextBox字段绑定到对象

时间:2017-05-23 16:58:42

标签: c# wpf xaml mvvm

嘿,如果你有一个对象,例如Person,其属性为FirstNameLastNameBirthDate。你需要单独购买每个房产吗?

在ViewModel.cs中这样:

private string _FirstName;
public string FirstName
{
     get { return _FirstName; }
     set 
     {
         _FirstName = value;
         RaisePropertyChanged("FirstName"); 
     }
}

这在View.xaml

<TextBox Text="{Binding FirstName, Mode=TwoWay}" />

我试过了:

<TextBox Text="{Binding Person.FirstName, Mode=TwoWay}" />

因此我不需要键入每个属性。这可能吗?究竟是怎么回事?

1 个答案:

答案 0 :(得分:0)

以下是一种模式:

<强>模型

public class Notifier : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class Person : Notifier 
{
    private string _firstName;

    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            RaisePropertyChanged(); //No need to pass "FirstName".
        }
    }
}

<强>视图模型

public class PersonViewModel : Notifier
{
    private Person _person;

    public Person Person
    {
        get { return _person; }
        set
        {
            _person= value;
            RaisePropertyChanged(); //No need to pass "Person".
        }
    }
}

查看(此视图的DataContext被假定为PersonViewModel类的实例)

<!-- other codes -->
<Grid DataContext="{Binding Person}">
    <!-- other codes -->
    <TextBox Text="{Binding FirstName, Mode=TwoWay}" />
    <!-- other codes -->
</Grid>
<!-- other codes -->