WPF Datagrid view header binding

僤鯓⒐⒋嵵緔 提交于 2019-12-17 21:35:49

问题


Actually the issue im facing is slight different than what title says. I try to sumarize the issue below.

Class PersonnelViewModel
{

public SelectedPersonnelItem PersonnelItemViewModel;

}

Class PersonnelItemViewModel
{

}

Data Context of the View is A whereas the Item source of the data grid is SelectedPersonnelItem which is a B type property in the class A. Now i want to bind the grid column to properties defiend within class A. But its not working as the context of the grid is another class (B). How can i solve this issue ?

XAML

<DataGrid Grid.Row="1"
          SelectedItem="{Binding SelectedPersonnelItem}"
          Name="PersonnelGrid"
          ItemsSource="{Binding PersonnelGridData}"
          event:DatagridRowDoubleClickHandler.MethodName="EditRecord"
          CanUserAddRows="False">
  <DataGrid.Columns>
    <DataGridTemplateColumn>
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <CheckBox IsChecked="{Binding IsItemChecked, UpdateSourceTrigger=PropertyChanged}"></CheckBox>
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTextColumn Header="Name/Company"
                        Binding="{Binding Name}" />
    <DataGridTextColumn Header="Qualification"
                        Binding="{Binding Qualification}" />
    <DataGridTextColumn Header="Arrival"
                        Binding="{Binding ArrivalDate}" />
    <DataGridTextColumn Header="Departure"
                        Binding="{Binding DepartureDate}" />
  </DataGrid.Columns>
</DataGrid> 

回答1:


You can access the parents datacontext using

Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
    AncestorType={x:Type DataGrid}}, Path=DataContext.ColumnName}" 

So to add a column showing A's Property do

<DataGridTextColumn Header="Company" Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.Company}"/>



回答2:


Finally I managed to get it working. If I directly bind the property to the column header its not populating the value.

I had to do as following:

<DataGridTextColumn Binding="{Binding Name}">
    <DataGridTextColumn.Header> 
        <TextBlock Text="{Binding DataContext.MyProp, 
                       RelativeSource={RelativeSource FindAncestor, 
                       AncestorType={x:Type Window}}}" /> 
    </DataGridTextColumn.Header>
</DataGridTextColumn>


来源:https://stackoverflow.com/questions/16653005/wpf-datagrid-view-header-binding

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