Question

I've got a Grid and a component inside it. The Grid has a custom DataContext while the children has to use the default .xaml.cs file.

Of course, changing the DataContext for the parent control changes it also for the children.

So I need to set the children's DataContext to the xaml.cs file.

I'm trying using DataContext="{Binding}" but it's not working.

How can I do that?

EDIT: Here's my code based on the replies

<UserControl x:Class="MyNamespace.MyClass"
x:Name="MyName"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:lsp="clr-namespace:LSPlugins"
xmlns:utils="clr-namespace:LSPlugins.Utilities"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="480" d:DesignWidth="480"> 

    <UserControl.Resources>
        <utils:ColorToSolidColorBrushValueConverter x:Key="ColorConverter"/>
        <lsp:MyModel x:Key="MyModel" x:Name="MyModel"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" DataContext="{StaticResource MyModel}" Background="{Binding Path=BackgroundColor, Converter={StaticResource ColorConverter}}" Opacity="{Binding Path=BackgroundOpacity}">        
        <ContentPresenter Content="{Binding PresenterContent}" DataContext="{Binding ElementName=MyName}"/>
    </Grid>
</UserControl>

I've tried with both Name and x:Name but it's still not working and it throws this exception:

System.Windows.Data Error: BindingExpression path error: 'PresenterContent' property not found on 'MyNamespace.MyModel' 'MyNamespace.MyModel' (HashCode=63183526). BindingExpression: Path='PresenterContent' DataItem='MyNamespace.MyModel' (HashCode=63183526); target element is 'System.Windows.Controls.ContentPresenter' (Name=''); target property is 'Content' (type 'System.Object')..

Was it helpful?

Solution

Try by binding the page element itself to the DataContext property:

DataContext="{Binding ElementName=phoneApplicationPage}

Or, in the code-behind (i.e xaml.cs file):

yourElement.DataContext = this;

EDIT:

Or, you can set the Content with a Binding by setting the source there:

Content="{Binding PresenterContent, ElementName=MyName}"

OTHER TIPS

You can name the parent control and then bind the children's DataContext using the ElementName:

DataContext="{Binding ElementName=TheWindow}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top