将控件属性绑定到Window ViewModel的Class的属性

时间:2013-08-06 10:20:01

标签: c# wpf binding

我想将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>

我也试过了 thisthis,但他们都没有为我工作。

1 个答案:

答案 0 :(得分:4)

您已在INotifyPropertyChanged上实施了ViewModel,但在Property更改时您从未致电

尝试:

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

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