我想保護DataGrid的某些行以防止用戶刪除,雖然屬性CanUserDeleteRows
設置爲true
。防止刪除DataGrid行
有沒有可能保護一些行,希望通過數據綁定或觸發器? ItemsSource綁定到T的ObservableCollection。
我想保護DataGrid的某些行以防止用戶刪除,雖然屬性CanUserDeleteRows
設置爲true
。防止刪除DataGrid行
有沒有可能保護一些行,希望通過數據綁定或觸發器? ItemsSource綁定到T的ObservableCollection。
如果您的綁定對象上有一個屬性可用於確定是否可以刪除當前行,如「IsDeleteEnabled」,那麼您可以將DataGrid的CanUserDeleteRows屬性綁定到SelectedItem.IsDeleteEnabled。
例如,
<DataGrid Name="dataGrid1"
CanUserDeleteRows="{Binding ElementName=dataGrid1, Path=SelectedItem.IsDeleteEnabled}"
從來沒有用DataGrid做過。通常,當我需要控制這樣的事情時,我使用一個ListBox和一個帶有Grid的DataTemplate來爲它提供一個Grid或一個帶有GridView的ListView的想法,因爲它們都可以讓您更好地控制交互。
由於您綁定了,所以您可以使用DataGridTemplateColumn.CellEditingTemplate並根據綁定對象中的邏輯創建您自己的Delete按鈕/文本,該文本是可見或啓用的。也許像這樣(我沒有測試這個,但它應該是一個你可以頭的方向)?
<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>
使用這種方法,因爲該命令被綁定到單獨的對象,你可能需要調高屏幕的視圖模型處理從刪除的ObservableCollection該行的事件。
再次,不知道這是最好的方式,但它是我的10分鐘刺傷它。所以如果太可怕了,請不要投我太多。
我對這個問題的興趣,如果有可能使用DataGrid的綜合刪除功能做沒有實現我自己的刪除處理。但是,無論如何,謝謝你的回答。 – HCL
+1好主意,但只有在禁用多項選擇的情況下才有效。我會測試它是否工作,因爲我認爲這是一個很好的解決方案,但我依賴於多選,並且這不起作用。 – HCL