防止删除DataGrid行

时间:2011-09-12 16:29:05

标签: wpf datagrid wpfdatagrid

我想保护DataGrid的某些行,以防止用户删除,但属性CanUserDeleteRows设置为true

是否有可能保护某些行,希望通过数据绑定或触发器? ItemsSource绑定到一个Ob的ObservableCollection。

2 个答案:

答案 0 :(得分:13)

如果绑定对象上有一个属性可用于确定是否可以删除当前行,如'IsDeleteEnabled',则可以将DataGrid的CanUserDeleteRows属性绑定到SelectedItem.IsDeleteEnabled。

例如,

<DataGrid Name="dataGrid1" 
        CanUserDeleteRows="{Binding ElementName=dataGrid1, Path=SelectedItem.IsDeleteEnabled}" 

答案 1 :(得分:0)

从未使用DataGrid完成此操作。通常,当我需要控制这样的东西时,我使用一个ListBox和一个带有Grid的DataTemplate来为它提供一个Grid或一个带有GridView的ListView的概念,因为它们都可以让你更好地控制交互。

在黑暗中拍摄,因为您正在绑定,您可以使用DataGridTemplateColumn.CellEditingTemplate并根据绑定对象中的逻辑创建自己的删除按钮/文本,该按钮/文本是可见的或启用的。也许这样的事情(我没有测试过,但它应该是你可以指导的方向)?

<dg:DataGridTemplateColumn Header="Action">
    <dg:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Text Content="Delete" />
        </DataTemplate>
    </dg:DataGridTemplateColumn.CellTemplate>

    <dg:DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ButtonEnabled="{Binding Path=IsDeleteEnabled, Mode=OneWay}" Content="Delete" Command="{Binding Path=DeleteMe}" />
        </DataTemplate>
    </dg:DataGridTemplateColumn.CellEditingTemplate>
</dg:DataGridTemplateColumn>

使用此方法,由于命令绑定到单个对象,您可能必须引发屏幕的ViewModel处理的事件,以从ObservableCollection中删除该行。

再次,不确定这是否是最佳方式,但这是我10分钟的刺伤。所以,如果它太可怕了,请不要过多地投票给我。