简体   繁体   中英

Setting DataContext to xaml.cs file

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')..

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

DataContext="{Binding ElementName=phoneApplicationPage}

Or, in the code-behind (ie 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}"

您可以命名父控件,然后使用ElementName绑定子控件的DataContext:

DataContext="{Binding ElementName=TheWindow}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM