Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

c# - binding to a property of an object

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).

CurrentPerson consists of Name and Age properties

Inside the ViewModel:

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

Xaml :

<TextBox Text="{Binding Name}" >
<TextBox Text="{Binding 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.

How should I achieve this ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.

Simple example:

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 ...
}

Now your xaml would be:

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

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...