WinRT XAML Databinding: How to bind to a property to the parent's data context when binding within an ItemTemplate?

白昼怎懂夜的黑 提交于 2020-01-05 08:13:30

问题


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.

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.

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.

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>

回答1:


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

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


来源:https://stackoverflow.com/questions/29483761/winrt-xaml-databinding-how-to-bind-to-a-property-to-the-parents-data-context-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!