2

I have a Page which contains a User Control, the Page's Data Context is bound, and so is the Contained User Control. When the Page is displayed, I can see that the User Control in the Page is displaying the values from the element as I would expect, such as Title and Description, however, in the Code Behind on the same User Control, the Data Context is null.. What am I doing wrong?

I need the Data Context so I could edit it's values within the control or change other UI elements within the page. What am I doing wrong here?

MyPage:

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
DataContext="{Binding}"

The use of the User Control with that page:

<Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0">
       <local:ucFooControl DataContext="{Binding}"/>
</Grid>

Then, where I am seeing null in User Control Code Behind, even though display elements are showing bound items.

public ucFooControl()
{
    this.InitializeComponent();

    if (this.DataContext != null)
    {
        bar= (Bar)DataContext;
        this.DoSomething((bar);
    }
}
Wizard
  • 1,142
  • 3
  • 16
  • 36

1 Answers1

1

Try this:

        public MyUserControl1()
        {
            this.InitializeComponent();
            DataContextChanged += OnDataContextChanged;
        }

        private void OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
        {
            if (this.DataContext != null)
            {
               bar = (Bar)DataContext;
               this.DoSomething((bar);
            }
        }
Nguyen Kien
  • 1,897
  • 2
  • 16
  • 22