Skip to content

Raise CommandInvalidate when adding or removing elements on collection #87

@Daimonion1980

Description

@Daimonion1980

Hello Thomas.

Is it possible to raise a CommandInvalidate method when changing the number of elements on an ObservableCollection?

In my code i have an ObservableCollection where i can add or remove elements via command methods.
Now I want to implement a clear button which will become enabled when the ObservableCollection has more than zero elements.

[ViewModel]
[ViewModelGenerateFactory]
public partial class VM_ParameterChooser 
{
	[Property] ObservableCollection<VM_Parameter> selectedParameterList = new ObservableCollection<VM_Parameter>();

	[Command(CanExecuteMethod = nameof(SelectedListCanBeCleared))]
	public void Clear()
	{
		SelectedParameterList.Clear();
	}

	//this method is only called when SelectedParameterList is changed itself
	//but should be called if a element is added or removed from the collection
	[CommandInvalidate(nameof(SelectedParameterList))]	
	public bool SelectedListCanBeCleared() => SelectedParameterList.Count > 0;

	[Command]
	public void AddSelectedParameter(object param)
	{
		var selectedParam = param as VM_Parameter;
		if (selectedParam is null) return;
		SelectedParameterList.Add(selectedParam);
	}

	[Command]
	public void RemoveSelectedParameter(object param)
	{
		var selectedParam = param as VM_Parameter;
		if (selectedParam is null) return;
		SelectedParameterList.Remove(selectedParam);
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions