【问题标题】:Bind an control property to a property of a Class of the Window ViewModel将控件属性绑定到窗口 ViewModel 的类的属性
【发布时间】:2013-08-06 10:20:00
【问题描述】:

我想将 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,但没有一个对我有用。

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    你已经在你的ViewModel 上实现了INotifyPropertyChanged,但是当Property 改变时你永远不会调用它

    尝试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 2017-08-08
      • 2015-01-25
      • 1970-01-01
      相关资源
      最近更新 更多