我有以下情况:
Window
|_Grid
|_ListView (MainProductGrid)
|_View
|_GridView
|_GridViewColumn
|_CellTemplate
|_DataTemplate
|_Label (LabelID)
现在,我想在 LabelID 中显示 ListView 中行的索引。 所以我做了以下事情:
<ListView ItemsSource="{Binding Path=ProductItems}" AlternationCount="{Binding Path=ProductItems.Count}">
...
对于标签,我有以下内容:
<Label x:Name="LabelID"
Content="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},
Path=(ListView.AlternationIndex)}"/>
但是它的LabelID只显示0.. 所以我认为 TemplatedParent 没有指向 ListView 控件。 那么我如何更正绑定(bind)以指向“上级父级”,在我的例子中是 ListView ?
提前致谢
################更新: 这是完整的 xaml ...
<Grid x:Name="mainGrid">
<ListView ItemsSource="{Binding Path=ProductItems}" AlternationCount="{Binding Path=ProductItems.Count}" x:Name="MainProductGrid">
<ListView.View>
<GridView AllowsColumnReorder="False">
<GridViewColumn x:Name="gvc" Header="id" Width="auto">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding (ListView.AlternationIndex),RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Product name" DisplayMemberBinding="{Binding Path=ProductName}" Width="auto" />
</GridView>
</ListView.View>
</ListView>
</Grid>
最佳答案
请尝试:
<Label Content="{Binding (ListView.AlternationIndex),
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}" />
更新:
这是正确的 xaml,绑定(bind)应设置为 RelativeSource=ListViewItem
,但网格列宽度存在问题:
<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>
关于wpf - 绑定(bind)到父控件中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15789090/