bind to a property in the parent control

前端 未结 3 1513
一向
一向 2020-12-31 05:08

i have the following case:

Window
  |_Grid
      |_ListView (MainProductGrid)
           |_View
               |_GridView
                    |_GridViewColum         


        
相关标签:
3条回答
  • 2020-12-31 05:35

    Well since you're in the context of a DataTemplate you cannot access the property via TemplatedParent mode, at least in your case. It refers to the element to which the template (in which the data-bound element exists) is applied. [...] Link I'm not sure, that it can be used in a DataTemplate because I've only seen it in ControlTemplates, but since the docs are not telling otherwise...

    What you can do is to try find the Ancestor. E.g.

    <Label Content="{Binding AlternationIndex, 
           RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}" ... />
    

    I didn't used in DataTemplates yet, so no warranty.

    0 讨论(0)
  • 2020-12-31 05:46

    please try this :

     <Label Content="{Binding (ListView.AlternationIndex),
        RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}"  />
    

    Update: here is the corret xaml, the binding should be to relativae source=ListViewItem, yet there was a problem with the grid column width:

      <ListView.View>
                <GridView AllowsColumnReorder="False">
                    <GridViewColumn x:Name="gvc" Header="id"  Width="30">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding (ListView.AlternationIndex),
                                    RelativeSource={RelativeSource FindAncestor,
                                        AncestorType={x:Type ListViewItem}}}"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
    
                    <GridViewColumn Header="Product name" 
                                    DisplayMemberBinding="{Binding Path=ProductName}"  
                                    Width="auto" />
                </GridView>
            </ListView.View>
    
    0 讨论(0)
  • 2020-12-31 05:57

    You can use

    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}} 
    

    to find a specific control above you

    0 讨论(0)
提交回复
热议问题