我有一种情况需要有条件地对wpf datagrid单元格进行只读。 DataGridCell中有IsReadOnly属性。但不幸的是,该财产是只读!有什么办法吗?
蚂蚁。
我有一种情况需要有条件地对wpf datagrid单元格进行只读。 DataGridCell中有IsReadOnly属性。但不幸的是,该财产是只读!有什么办法吗?
蚂蚁。
你应该可以使用 DataGrid.BeginningEdit 有条件地检查单元格是否可编辑的事件,然后在事件args上设置Cancel属性,如果没有。
与上面的Goblin类似的解决方案,但有一些代码示例:
想法是动态切换 CellEditingTemplate
在两个模板之间,一个与中的模板相同 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
切换 ContentTemplate
的 ContentPresenter
,所以上面两个模板可以动态切换 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
解决此问题的另一个非常简单的方法是使用DataGridCell的Style
<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属性。
这不会使单元格只读,但禁用。除了无法选择之外几乎是一回事。由于这个原因,此解决方案可能不适用于所有情况。
您还可以使用TemplateSelector属性根据您的逻辑设置两个不同的DataTemplates(一个可写和一个只读)?只需创建一个继承自DataTemplateSelector的类并覆盖SelectTemplate()方法(此处您可以访问datacontext)。