DataGrid禁用行wpf

时间:2012-10-14 12:56:13

标签: wpf datagrid

我有一个DataGrid,用户只能使用绑定到视图模型的add命令输入新行。下面显示的附加行为激活了正确的单元格。

我现在要做的是有效地使新行“模态”。也就是说,我不希望用户能够对网格执行任何其他操作,直到新行有效并提交,或者编辑被取消。

假设我的视图模型知道它何时有效并实现IEditableObject,我可以从我的附加行为中获得所有这些吗?必须做什么?

干杯,
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();
    }
}

2 个答案:

答案 0 :(得分:1)

This post给了我一个如何做到这一点的线索,粗略地说:

  1. 将IsReadOnly属性添加到绑定视图模型项
  2. 将IsNew属性添加到绑定视图模型项
  3. 在vm中,在实际添加项目之前,设置所有现有项目IsReadOnly = true
  4. 编辑新添加的项目或取消编辑时,将所有项目的IsReadOnly设置为false
  5. 修改类似于发布答案的行为(奇怪的是,这不是接受的答案)但没有ReadOnlyService
  6. 设置DataGridRow的样式
  7. 支付

    enter image description here

    enter image description here

答案 1 :(得分:0)

<DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}">
        <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
    </Style>
</DataGrid.RowStyle>
相关问题