Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c# - WPF Datagrid view header binding

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> 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...