绑定在WPF Datagrid第二行标头中不起作用

时间:2013-12-31 08:25:10

标签: c# wpf datagrid

我的Xaml -

 <Grid>
        <DataGrid Name="DataGrid" AutoGenerateColumns="False">
            <DataGrid.RowHeaderTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
                        <TextBlock Text="19" />
                        <TextBlock Text="{Binding Path=Items.Year, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGridRowHeader}}" Foreground="#9493CF" FontSize="16" />                        
                    </StackPanel>
                </DataTemplate>
            </DataGrid.RowHeaderTemplate>
            <DataGrid.Columns>                
                <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" />
                <DataGridTextColumn Header="Course" Binding="{Binding Path=Course}" />
            </DataGrid.Columns>        
        </DataGrid>
    </Grid>

在C#中

  var itemList = new List<Items>();

  itemList.Add(new Items { Year = 22, Course = "B.SC", Name = "Jegadees" });
  itemList.Add(new Items { Year = 23, Course = "M.SC", Name = "Arun" });
  itemList.Add(new Items { Year = 55, Course = "B.Tech", Name = "Kanaga" });

  DataGrid.ItemsSource = itemList;

项目集 -

 public class Items
    {        
        public string Name { get; set; }
        public string Course { get; set; }
        public int Year { get; set; }
    }

enter image description here

2 个答案:

答案 0 :(得分:3)

具有Item的DataContext的祖先是相应DataGridRowHeader的DataGrid行

 <TextBlock Text="{Binding Path=DataContext.Year, 
                           RelativeSource={RelativeSource Mode=FindAncestor, 
                                            AncestorType=DataGridRow}}" /> 

答案 1 :(得分:1)

使用这段代码RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGridRowHeader}}",您将前往Visual Tree,直到找到第一个DataGridRowHeader

问题出在您的路径中 - Path=Items.Year

它会搜索DataGridRowHeader中的属性Items,显然它没有。

您需要将路径更改为此DataContext.Year,因为DataContext将为您提供绑定到的实际对象,即Items类的实例,然后绑定到其属性Year在那个例子中。

所以正确的绑定就是这样的:

<TextBlock Text="{Binding Path=DataContext.Year,
                 RelativeSource={RelativeSource Mode=FindAncestor, 
                                    AncestorType=DataGridRowHeader}/>