How to bind delete action (in WPF Datagrid) to a c

2019-02-06 11:13发布

I have a datagrid and a view model that has an Observable collection of "Person" class which serves as ItemSource for the datagrid.

The Datagrid has two text columns "FirstName" and "LastName"

The datagrid has "CanUserAddRows" and "CanUserDeleteRows" set to true. So the user can add new rows and delete them by using the delete button.

When the user tries to delete a row, i want to validate if he can delete that or not. If he can delete it it will be deleted else the error will be shown and the row cannot be deleted. Something like we have in relay command

New RelayCommand(parm => this.DeletePerson(parm),this.CanDeletePerson(parm)

Is this possible ? If so how ?

  • Girija

标签: wpf mvvm
2条回答
虎瘦雄心在
2楼-- · 2019-02-06 11:21

Bind a property to CanUserDeleteRows.

XAML:

CanUserDeleteRows="{Binding UserCanDelete}"

ViewModel:

    public bool UserCanDelete
    {
        get
        {
            // return a value based on the currently selected item and business rules
        }
    }

Make sure you're raising a PropertyChanged event for this property somewhere, where you do that would depend on the other data changes that affect your return value.

查看更多
爷、活的狠高调
3楼-- · 2019-02-06 11:29

Try setting your DataGrid to ...

CanUserDeleteRows="False" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}"

and adding ...

<DataGrid.InputBindings>
    <KeyBinding Key="Delete" Command="{Binding DeletePersonCommand}" />
</DataGrid.InputBindings>

Add SelectedPerson to your VM and perform your delete validation based on the SelectedPerson in the DeletePersonCommand (ICommand) Execute or CanExecute and remove the item from the ObservableCollection if validation passes.

查看更多
登录 后发表回答