Emlyn
Emlyn

Reputation: 730

Binding to a ViewModel's Child Class Properties

I'm struggling to be able to bind a StatusBarItem content element in my view to a subclasses property in my ViewModel, I'm using the MVVM-Light framework/

ViewModel:

public class PageMainViewModel : ViewModelBase
{
    LoggedOnUserInfo UserInfo;

    public LoggedOnUser UserInfo
    {
       set
       {
          _UserInfo = value;
          RaisePropertyChanged("UserInfo");
       }
    }
}

For full clarity the LoggedOnUser Class is defined as follows

public class LoggedOnUser : INotifyPropertyChanged
{
    private string _Initials;        

    public event PropertyChangedEventHandler PropertyChanged;            

    public LoggedOnUser()
    {

    }

    [DataMember]
    public string Initials
    {
        get { return _Initials; }
        set 
        { 
             _Initials = value;
            OnPropertyChanged("Initials");
        }
    }

    protected void OnPropertyChanged(string propValue)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propValue));
        }
    }

}

My Views DataContext is being set and is working as I am able to see other bindings working, but my attempts to bind to UserInfo.Initials property in my XAML are producing an empty result.

XAML:

<StatusBarItem Grid.Column="0" Content="{Binding UserInfo.Initials}" Margin="5,0,0,0" VerticalAlignment="Center" Focusable="False" />

The UserInfo property is set after the viewModel is created due to several factors but I thought with my propertychanged events this would be ok.

Any Advice on this would be greatly appreciated.

Upvotes: 0

Views: 2275

Answers (3)

blindmeis
blindmeis

Reputation: 22445

add the getter to your userinfo

public class PageMainViewModel : ViewModelBase
{
  LoggedOnUserInfo UserInfo;

  public LoggedOnUser UserInfo
  {
     get {return _UserInfo;}
     set
     {
        _UserInfo = value;
        RaisePropertyChanged("UserInfo");
     }
  }
}

and like H.B. said - check your output window for binding errors

Upvotes: 1

marc wellman
marc wellman

Reputation: 5886

I am not quite sure why you have the initials_ attribute bound inside the UserInfo_ attribute. You can't access the initials_ attribute without a getter of the UserInfo_ attribute.

I would suggest to bind to the latter separately.

Upvotes: 0

brunnerh
brunnerh

Reputation: 185280

You do not appear to have a getter on UserInfo, the binding will be out of luck.

(Also check for binding errors when having trouble with bindings, they probably will tell you about all their problems)

Upvotes: 2

Related Questions