Running "CanExecute" in postharp [Command] when changing a document?

I am currently migrating the project to PostSharp to remove a lot of code templates, most of them go very smoothly, but I can’t figure out how to get the team to double-check if it is CanExecute . I expected PostSharp to test the command, as if properties are checking dependencies, here is a minimalist pattern

 [NotifyPropertyChanged] public class MyWindowViewModel { /// Anything bound to this refreshes just fine as expected public ObservableCollection<SomeType> Documents = new ObservableCollection<SomeType>(); [Command] public ICommand AddDocumentCommand { get; set; } public void ExecuteAddDocument () { Documents.Add(new SomeType()); } [Command] public ICommand CloseDocumentCommand { get; set; } public bool CanExecuteCloseDocument () => Documents.Any(); public void ExecuteCloseDocument () { Documents.Remove(Documents.Last()); } } 

At startup, the collection is empty, and the button attached to the close command is marked as expected, however adding a document using the button attached to AddDocument does not activate the close button of the document, which is a suitable way to execute What do I need? Is PostSharp just a consideration of assignments, not method calls as changes, or is it something else entirely?

+7
c # wpf postsharp
source share
1 answer

According to Command documentation

CanExecuteCloseDocument must be a property

 public bool CanExecuteCloseDocument => Documents.Any(); 

The method option is used when the command requires parameters,

Checking the availability of commands, which depends on the input argument, can be implemented as a method.

eg

 public bool CanExecuteCloseDocument (int blah) => Documents.Any(); public void ExecuteCloseDocument (int blah) { Documents.Remove(Documents.Last()); } 

That aside, the main problem here is that the view is not aware of changes to the collection, in order to know to update property changes.

Refer to this http://www.postsharp.net/blog/post/Announcing-PostSharp-42-RC

Collection Dependencies

When you add the [AggregateAllChanges] attribute to a field or automatic property, any change in the property of the object assigned to this field / property will be interpreted as a field / property change. The attribute now works only for collections.

 [NotifyPropertyChanged] public class MyWindowViewModel { /// Anything bound to this refreshes just fine as expected [AggregateAllChanges] // <-- when the collection changes to cause notification public ObservableCollection<SomeType> Documents { get; } = new ObservableCollection<SomeType>(); [Command] public ICommand AddDocumentCommand { get; set; } public void ExecuteAddDocument () { Documents.Add(new SomeType()); } [Command] public ICommand CloseDocumentCommand { get; set; } public bool CanExecuteCloseDocument => Documents.Any(); public void ExecuteCloseDocument () { Documents.Remove(Documents.Last()); } } 
+7
source share

All Articles