Search code examples
c#wpfdatacontext

How to set DataContext from codebehind


if i try to set my DataContext via Button_Click the child doesn't get it inherited. What do i miss here?

Simple Test example:

XAML

<StackPanel>
    <Button Content="Add Datacontext"
            Height="50" Click="Button_Click"/>
    <ContentControl Name="Test"/>
</StackPanel>

Code Behind

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Test.DataContext = DateTime.Now;
    }

Result

The ContentPresenter which is generated in the ContentControl is after the click still null but should be DateTime.

enter image description here


Solution

  • the DataContext for the ContentControl is set, you are inspecting the ContentPresenter within the ContentControl...

    <ContentControl Name="Test" Content="{Binding}">
    

    will fix it.