Search code examples
c#wpfdata-bindingdatacontext

How can I bind to the View's DataContext and not the innermost DataContext?


Some pseudo-code to serve as an example:

<UserControl>
    <UserControl.DataContext>
        <vm:MyViewModel />
    </UserControl.DataContext>

    <Grid>
        <StackPanel DataContext="{Binding SomeOtherContext}">
            <TextBlock Text="{Binding MyString}" />
            <Grid DataContext="THE FIRST CONTEXT">
                <TextBlock Text="{Binding PropertyFromFirstContext}" />
            </Grid>
        </StackPanel>
    </Grid>
</UserControl>

So, what I am looking for is the binding syntax necessary in place of "THE FIRST CONTEXT" to make the innermost TextBlock binding pull its property from the outermost DataContext, and not the one set at the intermediate StackPanel.

I've found examples like this one that suggest a way of doing it in the TextBlock binding, but if I had a mass of controls in there, that's a lot of extra coding. I would rather set a new DataContext at that particular scope so that the inner binding syntax is cleaner to read.


Solution

  • Try the following:

    <UserControl x:Name="Parent">
        <UserControl.DataContext>
            <vm:MyViewModel />
        </UserControl.DataContext>
    
        <Grid>
            <StackPanel DataContext="{Binding SomeOtherContext}">
                <TextBlock Text="{Binding MyString}" />
                <Grid DataContext="{Binding DataContext, ElementName=Parent}">
                    <TextBlock Text="{Binding PropertyFromFirstContext}" />
                </Grid>
            </StackPanel>
        </Grid>
    </UserControl>