DataGrid禁用行WPF [英] DataGrid disabling rows wpf
问题描述
我有一个DataGrid,用户只能使用绑定到视图模型的add命令输入新行。下面显示的附加行为将激活正确的单元格。
I have a DataGrid where the user can only enter new rows using an add command bound to a view model. The attached behavior shown below activates the correct cell.
我现在要做的是有效地使新行成为模态。也就是说,在新行有效并提交或取消编辑之前,我不希望用户对网格进行任何其他操作。
What I want to do now is effectively make the new row 'modal'. That is, I don't want the user to be able to do anything else with the grid until the new row is valid and committed, or the edit is cancelled.
假设我的视图模型知道它何时有效并实现IEditableObject,是否可以从附加的行为中获得所有这些?必须做什么?
Assuming my view model knows when it is valid and implements IEditableObject, can I get all of that out of my attached behavior? What must be done?
干杯,
Berryl
Cheers,
Berryl
public class NewItemAddedByCommandBehavior : Behavior<DataGrid>
{
private MainWindowViewModel _vm;
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.DataContextChanged += OnAssociatedObject_DataContextChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.DataContextChanged -= OnAssociatedObject_DataContextChanged;
_vm.NewItemAddedByCommand -= OnNewItemAddedByCommand;
}
private void OnAssociatedObject_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
_vm = (MainWindowViewModel) AssociatedObject.DataContext;
_vm.NewItemAddedByCommand += OnNewItemAddedByCommand;
}
private void OnNewItemAddedByCommand(object sender, EventArgs e)
{
var currentItem = _vm.SelectedItem;
var col = AssociatedObject.Columns[1];
AssociatedObject.CurrentCell = new DataGridCellInfo(currentItem, col);
AssociatedObject.ScrollIntoView(currentItem, col);
AssociatedObject.Focus();
AssociatedObject.BeginEdit();
}
}
推荐答案
< a href = https://stackoverflow.com/questions/2030143/wpf-datagrid-with-some-read-only-rows/8828485#comment17449624_8828485>这篇文章给了我一个思路,大致:
This post gave me a clue how to do this, roughly:
- 将IsReadOnly属性添加到绑定视图模型项中
- 将IsNew属性添加到绑定视图模型项
- 在虚拟机中,在实际添加该项之前,请在新添加的项为时设置所有现有项IsReadOnly = true
- 编辑或取消其编辑,将所有项目的IsReadOnly设置为false
- 修改类似于发布答案的行为(奇怪的是,它不是可接受的答案),但是没有ReadOnlyService
- 设置DataGridRow的样式
- Add an IsReadOnly property to the bound view model item
- Add an IsNew property to the bound view model item
- In the vm, before actually adding the item, set all existing items IsReadOnly = true
- when the newly added item is edited or its edit canceled, set IsReadOnly for all items back to false
- Modify the behavior similar to the posting answer (which oddly enough was not the accepted answer) but without the ReadOnlyService
- Style the DataGridRow
收获
the payoff
这篇关于DataGrid禁用行WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!