WinRT XAML 数据绑定:在 ItemTemplate 中绑定时如何将属性绑定到父级的数据上下文?

问题描述:

我有一个 GridView,我以编程方式将数据上下文设置为视图模型实例.GridView 的 ItemsSource 绑定到一个可观察集合 (PagesToRead),它是视图模型上的一个属性.

I have a GridView for which I set the data context programmatically to the view model instance. The GridView's ItemsSource is bound to an observable collection (PagesToRead) which is a property on the view model.

GridView.ItemTemplate 中,绑定与 ItemsSource 中的 observable 集合背道而驰,但我想将 StackPanel 的 Background 元素绑定到视图模型上的不同属性.

Within the GridView.ItemTemplate, binding goes against the observable collection in the ItemsSource, but I want to bind the StackPanel's Background element to a different property on the view model.

我正在寻找神奇的 <Background="{Binding Path=BackgroundColor, Source=???}"> 它将转义当前的 ItemsSource 并绑定到 视图模型上的 BackgroundColor 属性.

I'm looking for the magic <Background="{Binding Path=BackgroundColor, Source=???}"> that will escape the current ItemsSource and bind to the BackgroundColor property on the view model.

这是省略的 XAML:

Here's the elided XAML:

<Grid>
  <GridView x:Name="MainGrid" CanReorderItems="True" CanDragItems="True" 
    ItemsSource="{Binding Path=PagesToRead}"
    <GridView.ItemTemplate>
      <DataTemplate >
          <StackPanel>
            <Background="{Binding Path=BackgroundColor, Source=???}">
            <TextBlock Text="{Binding Path=Title}" 
          </StackPanel>
      </DataTemplate>
    </GridView.ItemTemplate>
  </GridView>
</Grid>

我通过另一条途径得到了答案(感谢 Karl Erickson).你要做的是:

I got an answer via another avenue (thanks Karl Erickson). What you do is:

<StackPanel Background="{Binding Path=DataContext.TileBackgroundColor,
                         ElementName=MainGrid">