binding to a property of an object

后端 未结 2 711
忘了有多久
忘了有多久 2020-12-16 14:05

I want to bind a series of TextBoxes in a grid into properties of an object which is itself another property in my ViewMod

相关标签:
2条回答
  • 2020-12-16 14:33

    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>
    
    0 讨论(0)
  • 2020-12-16 14:43

    Try this:

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

    Essentially, you can drill down into properties by using the . separator.

    For future reference, if you want to drill down into collections, you can use MyCollection[x] just like you would in code (where x would be replaced by a hard-coded number, not a variable).

    0 讨论(0)
提交回复
热议问题