Question

I tried to bind ObservableCollection<UserProfile> UsersList to pages DataContext, but program keeps telling me, that he cannot find UsersList although I can see it's values in OutPut using Debug.WriteLine. But on the other hand, if I add DataContext in C# code, everything works perfectly. What am I doing wrong?

C# code:

this.DataContext = new UsersViewModel(); //inside MainPage constructor

XAML code:

DataContext="{Binding UsersViewModel, RelativeSource={RelativeSource Self}}" //inside <page .../>
Was it helpful?

Solution

try to set binding this way instead :

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Your current binding means, bind data context to a property named UsersViewModel declared in it self. That will work if, for example, you have something like this in code behind :

public UsersViewModel UsersViewModel { get; set; }

then DataContext will be set to that property.

UPDATE :

Looking at your answer, you can try do it this way to set DataContext in Page level :

<Page.DataContext>
    <local:UsersViewModel />
</Page.DataContext>

OTHER TIPS

Ok, I got it work now, but in this case I don't bind anything on page itself, but on grid.

<Page.Resources>
    <local:UsersViewModel x:Key="UsersViewModel" />
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" DataContext="{StaticResource UsersViewModel}">

Is this good solution?

The UserViewModel should be an accessible object in the MainPage.xaml.cs code behind. You can have something like

public UsersViewModel UsersViewModel { get {return _usersViewModel; } private set { _usersViewModel = value;} }

You have to use the object name instead of the class name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top