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

时间:2010-06-01 03:27:31

标签: wpf datagrid wpfdatagrid

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

4 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分: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>

然后使用其他ContentPresenter图层定义数据模板,并使用Trigger切换ContentTemplate的{​​{1}},以便上述两个模板可以动态切换ContentPresenter绑定:

IsEditable

HTH

答案 2 :(得分:2)

此问题的另一个非常简单的解决方案是使用DataGridCell的样式

<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属性。

这不会使单元格只读但禁用。除了无法选择之外几乎是一回事。由于这个原因,此解决方案可能并不适用于所有情况。

答案 3 :(得分:0)

您还可以使用TemplateSelector属性根据您的逻辑设置两个不同的DataTemplates(一个可写和一个只读)?只需创建一个继承自DataTemplateSelector的类并覆盖SelectTemplate()方法(此处您可以访问datacontext)。