title | author | date | CreateTime | categories |
---|---|---|---|---|
wpf 绑定 DataGridTextColumn |
lindexi |
2018-08-10 19:16:53 +0800 |
2018-2-13 17:23:3 +0800 |
WPF |
本文告诉大家如何在 DataGridTextColumn 使用绑定,因为很容易绑定就找不到数据。
使用 DataGrid 有一个坑,就是 Columns 的数据绑定拿不到数据。
例如下面的代码
<Grid>
<DataGrid x:Name="MyDataGrid" ItemsSource="{Binding DataList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
<DataGridTextColumn Header="Property1" Binding="{Binding Property1}"/>
<DataGridTextColumn Header="Property2" Binding="{Binding Property2}"/>
<DataGridTemplateColumn Header="Total">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding>
<Binding Path="Property1"/>
<Binding Path="Property2"/>
<MultiBinding.Converter>
<local:MyValueConverter/>
</MultiBinding.Converter>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
可以看到绑定了DataGridTextColumn Header="Property1" Binding="{Binding Property1}"
可以拿到数值,但是在MultiBinding
没有拿到数值,因为他在DataTemplate
而DataGridTemplateColumn
没有数据。
解决方法很简单,使用RelativeSource
找到数据。只需要修改<Binding Path="DataContext.Property2" RelativeSource="{RelativeSource AncestorType=DataGridCell}"/>
就可以。下面就是修改后的代码
<Grid>
<DataGrid x:Name="MyDataGrid" ItemsSource="{Binding DataList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
<DataGridTextColumn Header="Property1" Binding="{Binding Property1}"/>
<DataGridTextColumn Header="Property2" Binding="{Binding Property2}"/>
<DataGridTextColumn>
<DataGridTextColumn.Binding >
<MultiBinding >
<Binding Path="DataContext.Property1" RelativeSource="{RelativeSource AncestorType=DataGridCell}"/>
<Binding Path="DataContext.Property2" RelativeSource="{RelativeSource AncestorType=DataGridCell}"/>
<MultiBinding.Converter>
<local:MyValueConverter/>
</MultiBinding.Converter>
</MultiBinding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>