2013-08-06 129 views
3

我想將TextBox的Text屬性綁定到ViewModel屬性的子項。將控件屬性綁定到窗口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,但他們沒有爲我工作。

回答

5

您已經實現INotifyPropertyChangedViewModel但你永遠不把它當Property改變

嘗試:

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

    ................. 
相關問題