有条不紊地向WPF DataGridCell发送只读

Ant*_*Ant 11 wpf datagrid wpfdatagrid

我有一种情况需要有条件地对wpf datagrid单元格进行readonly.DataGridCell中有IsReadOnly属性.但不幸的是,该财产是只读!有什么办法吗?
蚂蚁.

Jos*_*osh 7

您应该能够使用DataGrid.BeginningEdit事件来有条件地检查单元格是否可编辑,然后在事件args上设置Cancel属性,如果没有.


小智 7

与上面的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>
Run Code Online (Sandbox Code Playgroud)

然后用附加ContentPresenter层定义一个数据模板并Trigger用来切换ContentTemplateContentPresenter,这样上面两个模板就可以通过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>
Run Code Online (Sandbox Code Playgroud)

HTH