How to bind delete action (in WPF Datagrid) to a command or property in view model

后端 未结 2 1608
有刺的猬
有刺的猬 2020-12-30 03:04

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 colum

相关标签:
2条回答
  • 2020-12-30 03:21

    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.

    0 讨论(0)
  • 2020-12-30 03:41

    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.

    0 讨论(0)
提交回复
热议问题