WPF Databinding: How do I access the “parent” data context?

ぐ巨炮叔叔 提交于 2019-11-26 00:45:51

问题


I have a list (see below) contained in a window. The window\'s DataContext has two properties, Items and AllowItemCommand.

How do I get the binding for the Hyperlink\'s Command property needs to resolve against the window\'s DataContext?

<ListView ItemsSource=\"{Binding Items}\">
  <ListView.View>
    <GridView>
      <GridViewColumn Header=\"Action\">
        <GridViewColumn.CellTemplate>
          <DataTemplate>
            <StackPanel>
              <TextBlock>

                <!-- this binding is not working -->
                <Hyperlink Command=\"{Binding AllowItemCommand}\"
                           CommandParameter=\"{Binding .}\">
                    <TextBlock Text=\"Allow\" />
                </Hyperlink>

              </TextBlock>
            </StackPanel>
          </DataTemplate>
        </GridViewColumn.CellTemplate>
      </GridViewColumn>
    </GridView>
  </ListView.View>
</ListView>

回答1:


You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...



回答2:


This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.




回答3:


This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.

RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"



来源:https://stackoverflow.com/questions/1127933/wpf-databinding-how-do-i-access-the-parent-data-context

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