简体   繁体   中英

Bind an control property to a property of a Class of the Window ViewModel

I want to Bind the Text Property of a TextBox to a Child of a of a Property of a ViewModel.

Here is my code:


foo.cs:

    public class foo()
    {
      public foo()
      {
        Bar = "Hello World";
      }

      public string Bar { Get; private Set;}
      //Some functions
    }

ViewModel.cs:

    public class ViewModel : INotifyPropertyChanged
    {
      public foo Property { Get; Set; }

      //some more properties

      public ViewModel()
      {

      }

      public event PropertyChangedEventHandler PropertyChanged;        
      protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));            
      }
    }

Window.xaml.cs:

    public ViewModel MyViewModel { get; set; }

    public Window()
    {
      MyViewModel = new ViewModel();
      this.DataContext = MyViewModel;
      MyViewModel.Property = new foo();
    }

Window.xaml:

    <!--
    Some controls
    -->

    <TextBox Text="{Binding Path=Property.Bar}"></TextBox>

I also tried this and this , but none of them worked for me.

You have implemented INotifyPropertyChanged on your ViewModel but you never call it when Property is changed

try:

public class ViewModel : INotifyPropertyChanged
{
  private foo _property;
  public foo Property
  { 
     get{ return _property; }
     set{ _property = value; OnPropertyChanged(); }
  }

  .................

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM