覆盖父datacontext

时间:2013-12-09 08:22:12

标签: c# xaml

我现在正在学习数据绑定,并且遇到了父母和子女数据文件的麻烦。

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
        DataContext="{Binding Group}"
        d:DataContext="{Binding Groups[0], Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>


 <StackPanel x:Name="SideData" Width="480" Margin="12,12,24,12" Grid.Row="1" HorizontalAlignment="Left" DataContext="{Binding SideItem}">
        <TextBlock x:Name="SideText"        Text="{Binding Title}" Margin="12,12,12,12" Style="{StaticResource SubheaderTextBlockStyle}" MaxHeight="60"/>
        <Image x:Name="SideImage"           Source="{Binding ImagePath}" Height="400" Width="400"  Margin="0,0,0,20" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
        <TextBlock x:Name="SideDescription" Text="{Binding Subtitle}" Margin="0,0,0,0" Style="{StaticResource BodyTextBlockStyle}"/>
    </StackPanel>

我想将Grid的DataContext保留在“Group”中,但我希望StackPanel中的所有控件都绑定到“SideItem”。

我确信我做错了,因为它工作不正常。当我将Grid的datacontext绑定到“SideItem”时,它可以正常工作,但这会改变整个事情,所以它毫无意义。帮助

此外,这是后端(我正在使用Visual Studio 2013模板):

private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
    // TODO: Create an appropriate data model for your problem domain to replace the sample data
    var group = await SampleDataSource.GetGroupAsync((String)e.NavigationParameter);
    this.DefaultViewModel["Group"] = group;
    this.DefaultViewModel["Items"] = group.Items;
    this.DefaultViewModel["SideItem"] = group.Items.First();
}

2 个答案:

答案 0 :(得分:0)

只需设置堆栈面板的datacontext:

<StackPanel DataContext="{Binding SideItem}" ...

答案 1 :(得分:0)

似乎SideItem应该是Group的属性,是吗?您的代码中的组是什么?

修改

如果要绑定到与窗口相关的SideItem,请尝试:

<StackPanel DataContext="{Binding SideItem, RelativeSource={RelativeSource AncestorType={x:Type Window}}}">