代码改变世界

How To Binding the DataContext Property To DataGrid

2012-02-20 10:40  barbarossia  阅读(339)  评论(0编辑  收藏  举报

When we use the NVVM design mode in wpf develop. We also binding some property to datagrid as well. For example we can define datagrid to binding a list in such place.

 <DataGrid  x:Uid="dgByKeys" 
ItemsSource="{Binding Keys}"
Style="{StaticResource DgNormalSty}"
ScrollBar.Scroll="ExportByKeys_Scroll"
ScrollViewer.ScrollChanged="ExportByKeys_ScrollChanged"
Sorting="ExportByKeys_Sorting"
Height="230"
HorizontalAlignment="Stretch"


But when we will want to binding a propoerty not include the list keys(it is not a key property),how we can binding it in datagrid element?

It is a solution:

 <DataGrid.Columns>
<DataGridTemplateColumn >
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate >
<CheckBox x:Uid="chkAllIsChecked"
IsThreeState="False"
IsChecked="{Binding IsAllChecked}"
DataContext="{Binding ElementName=tabGrid, Path=DataContext}"/>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate >
<CheckBox x:Uid="chkKeyIsChecked"
IsThreeState="False"
IsChecked="{Binding IsSelected,Mode=TwoWay, NotifyOnSourceUpdated=True,UpdateSourceTrigger=PropertyChanged}" Margin="4,0"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>


The property IsAllChecked is not key's property,it is context, so we define

DataContext="{Binding ElementName=tabGrid, Path=DataContext}"/>

And IsSelected is key's property,so we also define:

 <CheckBox x:Uid="chkKeyIsChecked" 
IsThreeState="False"
IsChecked="{Binding IsSelected,Mode=TwoWay, NotifyOnSourceUpdated=True,UpdateSourceTrigger=PropertyChanged}" Margin="4,0"/>


There is work perfect.