有条件地只读到WPF DataGridCell [英] Conditionally making readonly to WPF DataGridCell

查看:473
本文介绍了有条件地只读到WPF DataGridCell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种需要有条件地将其读取到wpf datagrid单元格的情况。 DataGridCell中有IsReadOnly属性。但不幸的是,这个财产是只读的!有什么办法吗?

ant。

I have a situation that needs to conditionally make readonly to wpf datagrid cell. There is IsReadOnly property in DataGridCell. But unfortunately, that property is readonly! Is there any way to do it?
ant.

推荐答案

类似于上面的Goblin解决方案,但是有一点代码示例:

The similar solution as Goblin above, but with a little code samples:

想法是在两个模板之间动态切换 CellEditingTemplate ,一个是相同的作为 CellTemplate 中的一个,另一个用于编辑。这使得编辑模式的作用与非编辑单元格完全相同,尽管它处于编辑模式。

The idea is to dynamically switch the CellEditingTemplate between two templates, one is the same as the one in the CellTemplate, the other is for editing. This makes the edit mode acts exactly the same as the non-editing cell although it is in edit mode.

以下是一些示例代码,请注意,方法需要 DataGridTemplateColumn

The following is some sample code for doing this, notice that this approach requires DataGridTemplateColumn:

首先,为只读和编辑单元格定义两个模板:

First, define two templates for read-only and editing cells:

<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 定义数据模板层,并使用触发器切换 ContentPresenter ContentTemplate ,所以上述两个模板可以通过 IsEditable 绑定动态切换:

Then define a data template with additional ContentPresenter layer and use Trigger to switch the ContentTemplate of the ContentPresenter, so the above two templates can be switched dynamically by the IsEditable binding:

<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

这篇关于有条件地只读到WPF DataGridCell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆