Anubhav Dhawan
Anubhav Dhawan

Reputation: 1487

Setting DataContext to current class results in an infinite loop

I am trying to set the DataContext property of a Page to the current class (not caring about the MVC concepts for now).

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

Now, I am getting trapped in an infinite loop. I know the reason, it is because I am initializing another object of MyPage class, from an object of MyPage class itself, which creates an infinite loop.

I can solve it by moving the part of the code which needs to be observed by the Views, in a class, say, Models (and then setting the DataContext property to that class). But, isn't there a way to reference the current class (without creating another instance) in XAML? Something like:

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

Upvotes: 0

Views: 131

Answers (2)

kirotab
kirotab

Reputation: 1306

  • DataContext="{Binding RelativeSource={RelativeSource Self}}" In xaml

  • this.DataContext = this; in code behind

Upvotes: 1

kkyr
kkyr

Reputation: 3845

<Page DataContext="{Binding RelativeSource={RelativeSource Self}}">

    ...

</Page>

Upvotes: 1

Related Questions