绑定到对象的属性 [英] binding to a property of an object

查看:80
本文介绍了绑定到对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在网格中绑定一系列文本框到对象的属性中,该对象本身是ViewModel中的另一个属性( DataContext).

I want to bind a series of TextBoxes in a grid into properties of an object which is itself another property in my ViewModel (the DataContext).

CurrentPersonNameAge属性组成

在ViewModel内部:

public Person CurrentPerson { get; set ... (with OnPropertyChanged)}

Xaml:

<TextBox Text="{Binding Name}" >
<TextBox Text="{Binding Age}" >

我不确定使用的方法,我在网格范围内设置了另一个DataContext,没有任何结果,还尝试再次设置源和路径(如Source = CurrentPerson,Path = Age),但没有任何结果,这些是为了试用,看看是否会有任何变化.

I wasn't sure on the approach to use, I set another DataContext in the grid scope, without any result, Also tried setting the source and path like Source=CurrentPerson, Path=Age again without any result, these were for trial and see if there would be any change or not.

我应该如何实现呢?

推荐答案

您的Person类成员NameAge是否自己提高了INPC?

Does your Person class members Name and Age raise INPC themselves?

如果要更新ViewModel中的NameAge的值并使其反映在视图中,则还需要它们引发在Person类中单独更改的属性.

If you want to update the value of either Name or Age in the ViewModel and have it reflect in the view, you need them to raise property changed individually inside Person class as well.

绑定很好,但是不会将视图模型的更改通知给视图.还请记住UpdateSourceTrigger,因为TextBox的默认值为LostFocus,因此将PropertyChanged设置为PropertyChanged将会在您键入时更新ViewModel中的字符串.

The bindings are fine, but the view is not notified of changes from the view model. Also remember UpdateSourceTrigger for a TextBox by default is LostFocus, so setting that to PropertyChanged will update your string in the ViewModel as you're typing.

简单的例子:

public class Person : INotifyPropertyChanged {
  private string _name;
  public string Name {
    get {
      return _name;
    }

    set {
      if (value == _name)
        return;

      _name = value;
      OnPropertyChanged(() => Name);
    }
  }

  // Similarly for Age ...
}

现在您的xaml是:

<StackPanel DataContext="{Binding CurrentPerson}">
  <TextBox Text="{Binding Name}" />
  <TextBox Margin="15"
            Text="{Binding Age}" />
</StackPanel>

或者您也可以按照@Kshitij的建议进行绑定:

or you can also bind as suggested by @Kshitij:

<StackPanel>
  <TextBox Text="{Binding CurrentPerson.Name}" />
  <TextBox Margin="15"
            Text="{Binding CurrentPerson.Age}" />
</StackPanel>

并在键入时更新视图模型:

and to update view model as you're typing:

<StackPanel DataContext="{Binding CurrentPerson}">
  <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
  <TextBox Margin="15"
            Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>

这篇关于绑定到对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆