将控件属性绑定到窗口ViewModel类的属性

3
我想将TextBox的Text属性绑定到ViewModel的一个属性的子属性上。 这是我的代码:
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>

我还尝试了这个这个,但都没对我起作用。
1个回答

4
你已经在你的ViewModel上实现了INotifyPropertyChanged,但当Property变化时你从未调用它。
尝试:
public class ViewModel : INotifyPropertyChanged
{
  private foo _property;
  public foo Property
  { 
     get{ return _property; }
     set{ _property = value; OnPropertyChanged(); }
  }

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接