我有一个情况,需要根据条件将WPF数据表格单元格设置为只读。在DataGridCell中有IsReadOnly属性,但不幸的是,该属性是只读的!有没有办法实现这个功能?
谢谢。
我有一个情况,需要根据条件将WPF数据表格单元格设置为只读。在DataGridCell中有IsReadOnly属性,但不幸的是,该属性是只读的!有没有办法实现这个功能?
谢谢。
CellEditingTemplate
与 CellTemplate
两个模板之间,其中一个与 CellTemplate
相同,另一个用于编辑。这使得编辑模式的操作方式与非编辑单元格完全相同。DataGridTemplateColumn
:<DataGrid>
<DataGrid.Resources>
<!-- the non-editing cell -->
<DataTemplate x:Key="ReadonlyCellTemplate">
<TextBlock Text="{Binding MyCellValue}" />
</DataTemplate>
<!-- the editing cell -->
<DataTemplate x:Key="EditableCellTemplate">
<TextBox Text="{Binding MyCellValue}" />
</DataTemplate>
</DataGrid.Resources>
</DataGrid>
接下来,使用额外的ContentPresenter
层定义数据模板,并使用Trigger
来切换ContentPresenter
的ContentTemplate
,这样上述两个模板就可以通过IsEditable
绑定动态切换:
<DataGridTemplateColumn CellTemplate="{StaticResource ReadonlyCellTemplate}">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<!-- the additional layer of content presenter -->
<ContentPresenter x:Name="Presenter" Content="{Binding}" ContentTemplate="{StaticResource ReadonlyCellTemplate}" />
<DataTemplate.Triggers>
<!-- dynamically switch the content template by IsEditable binding -->
<DataTrigger Binding="{Binding IsEditable}" Value="True">
<Setter TargetName="Presenter" Property="ContentTemplate" Value="{StaticResource EditableCellTemplate}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
HTH
<DataGrid>
<DataGrid.Resources>
<Style x:Key="disabledCellStyle" TargetType="DataGridCell">
<Setter Property="IsEnabled" Value="{Binding IsEnabled}" />
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn CellStyle="{StaticResource disabledCellStyle}" />
<DataGridCheckBoxColumn CellStyle="{StaticResource disabledCellStyle}" />
<DataGridTextColumn/> /*always enabled*/
</DataGrid.Columns>
</DataGrid>
这种样式假设ViewModel中有一个IsEnabled属性。
这不会使单元格只读,而是禁用它。虽然几乎是相同的,但它不能被选中。由于此原因,该解决方案可能并不适用于所有情况。