Triggering "CanExecute" on postsharp [Command] when a document changes? - c#

I am currently migrating a project to PostSharp to remove a lot of boilerplate code, most of it is going very smoothly but I'm left confused about how to force a command to recheck if it CanExecute. I expected PostSharp would inspect the command like it does properties to check for dependencies, here is a minimalist sample
[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 start the collection is empty and the button attached to the close command is greyed as expected, however adding a document through the button attached to AddDocument doesn't activate the close document button, what is the appropriate way to accomplish what I need? Is PostSharp only considering assignments and not method calls as changes or is it something else entirely?

According to their Command documentation
CanExecuteCloseDocument should be a property
public bool CanExecuteCloseDocument => Documents.Any();
The method option is used when the command requires parameters,
The command availability check that depends on the input argument can be implemented as a method.
for example
public bool CanExecuteCloseDocument (int blah) => Documents.Any();
public void ExecuteCloseDocument (int blah) { Documents.Remove(Documents.Last()); }
That aside the main issue here is that the view is unaware of the changes to the collection to know to refresh property changes.
Refer to this http://www.postsharp.net/blog/post/Announcing-PostSharp-42-RC
Dependencies to collections
When you add the [AggregateAllChanges] attribute to a field or
automatic property, any change to a property of the object assigned to
this field/property will be interpreted as a change to the
field/property itself. 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()); }
}

With PostSharp LINQ expression (or virtual calls, delegates, external methods) wouldn't work well for CanExecute's.
But expression on properties that implement INotifyPropertyChanged work fantastic (even for nested properties). ObservableCollection implements INotifyPropertyChanged, we don't need LINQ:
public bool CanExecuteCloseDocument => Documents.Count > 0;

Related

Setting action from function parameter is null

I have some actions in a view.
public class AView
{
public Action Show { get; set; }
public Action Hide { get; set; }
}
and I'm trying to set those actions inside another class, by passing them as a parameter (I don't want to pass the whole class)
_reloader.SetupActions(Show, Hide);
Reloader is abstract, because there might be different ways of handling how Hide/Show must behave depending on the scenario we're in.
public abstract class Reloader : IReloader
{
public void SetupActions(Action show, Action hide)
{
show = Show;
hide = Hide;
}
protected virtual void Show() { ... } //what should be done when Show is invoked
protected virtual void Hide() { ... } //same for Hiding
}
And for the current view, I might be using a RapidReloader, SafeReloader, etc. This bit is irrelevant, except that the injected reloader is specific to the current view.
Now my problem is simple and logic : when I'm in SetupActions, all parameters are null (because Actions haven't been set), and setting Show into null obviously does not work.
What can I do so that when Show.Invoke() happens my view, the ShowCode from the relevant reloader is called? I would like to avoid passing the whole view as a parameter.
Also, if you have a better design, I'm all ears. We might be in an XY problem situation
You will need to use System.ValueTuple nuget package if you don't use .Net Framework 4.7 or newer.
public interface IReloader
{
(Action Show, Action Hide) GetActions();
}
public abstract class Reloader : IReloader
{
public (Action Show, Action Hide) GetActions()
{
return (Show, Hide);
}
protected virtual void Show() { }
protected virtual void Hide() { }
}
public class FastReloader : Reloader { }
public class AView
{
public Action Show{ get; set; }
public Action Hide{ get; set; }
public void IwantTheNewActions()
{
var reloader = new FastReloader();
var actions = reloader.GetActions();
Show = actions.Show;
Hide = actions.Hide;
}
}

Updating UI when a model property changes in an ObservableCollection?

I have a view that has a group of images I get from a web service
I receive them in a list of this class:
public class ImageModel
{
public int Id { get; set; }
public string Name { get; set; }
public string imageUrl { get; set; }
}
under each image I show an up-vote button, so I added another bool property to the model above:
public bool UpVoted { get; set; }
the ListView that shows these images is bound to an ObservableCollection<ImageModel > , I want to change the voting icon through a converter that convert the value of UpVoted to the corresponding icon, when the user click the voting icon: a command execute this method:
private void OnVoting(ImageModel image)
{
Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;
}
the problem is that the UI is not updated, and to make sure that I understood the problem I turned the model to a View model and made the required changes to the UpVoted property (I'm using MVVM light library)
bool upVoted;
public bool UpVoted
{
get { return upVoted; }
set
{
Set(ref upVoted, value);
}
}
and it works now,
so I need to bind the UpVoted to the UI, so it's updated whenever it changed
first
your model class must inherit from MvxNotifyPropertyChanged
public class ImageModel : MvxNotifyPropertyChanged
{
public int Id { get; set; }
public string Name { get; set; }
private bool upVoted ;
public bool UpVoted
{
get { return upVoted ; }
set { upVoted = value; RaisePropertyChanged(() => UpVoted ); }
}
}
then with MvxValueConverter you ready to go
Mustafa's answer mentions a class that is specific to MvvmCross library.
Another alternative is TinyMvvm.
If you wish to write your own MVVM (or understand how MVVM works),
the general pattern is to implement INotifyPropertyChanged: Implement Property Change Notification, which I discuss here.
A convenient way to implement INotifyPropertyChanged, is to make a base class that does that implementation, then inherit from that base class. You can use the code in that sample as your base class. Or use a slightly different implementation, that avoids having to manually pass the property name as a string:
using System.ComponentModel;
using System.Runtime.CompilerServices;
// Use this as base class for all your "view model" classes.
// And possibly for your (domain) model classes.
// E.g.: "public class MyLoginViewModel : HasNotifyPropertyChanged".
// OR "public class MyLoginModel : HasNotifyPropertyChanged".
// Give it whatever name you want, for ViewModels I suggest "ViewModelBase".
public class HasNotifyPropertyChanged : INotifyPropertyChanged
{
// --- This is pattern to use to implement each property. ---
// This works for any property type: int, Color, etc.
// What's different from a standard c# property, is the "SetProperty" call.
// You will often write an IValueConverter (elsewhere) to use in XAML to convert from string to your property type,
// or from your property type to a type needed in your UI.
// Comment out this example property if you don't need it.
/// <summary>
/// Set to "true" at end of your initialization.
/// Then can use Property Trigger on Ready value=true in XAML to do something when your instance is ready for use.
/// For example, load something from web, then trigger to update UI.
/// </summary>
private bool _ready;
public bool Ready
{
get => _ready;
set => SetProperty(ref _ready, value);
}
public event PropertyChangedEventHandler PropertyChanged;
protected void SetProperty<T>(ref T property, T value, [CallerMemberName] string propertyName = null)
{
if (property == null || !property.Equals(value))
{
property = value;
RaisePropertyChanged(propertyName);
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Again, an alternative to the above code is to use an existing MVVM library.
For another alternative, that doesn't require writing "SetProperty(..)" or "OnPropertyChanged(..)" in all of your property setters, google for info about using Fody/PropertyChanged. Then you wouldn't need any of the above code; your class would simply inherit from INotifyPropertyChanged. (And in app startup, you call a method that "injects" the needed logic into all properties of all INotifyPropertyChanged classes.)
Acknowledgement: The code pattern in example above is based on one of the open source libraries. It might be from TinyMvvm.
you do not say which sort of container that you are using but not all controls are set to support two way notification by default. so you may have to add a
Mode=TwoWay
to get notifications from the back end that data has changed. Or as the previous answer by Mustafa indicated you may need to verify that your class is implementing the InotifyPropertyChanged event with mvvm light.

Using IObservable<T> to keep track of current state

Suppose I have an object that observes an IObservable so that it's always aware of the current state of some external source. Internally my object has a method that uses that external value as part of the operation:
public class MyObject
{
public MyObject(IObservable<T> externalSource) { ... }
public void DoSomething()
{
DoSomethingWith(CurrentT);
}
}
What's the idomatic 'reactive' way of using IObservable for 'tracking current state' instead of 'responding to stream of events'.
Idea #1 is to just monitor the observable and write down values as they come in.
public class MyObject
{
private T CurrentT;
public MyObject(IObservable<T> externalSource)
{
externalSource.Subscribe((t) => { CurrentT = t; });
}
public void DoSomething()
{
DoSomethingWith(CurrentT);
}
}
And that's fine, but keeping track of the state in a class member seems very un-reactive-y.
Idea #2 is to use a BehaviorSubject
public class MyObject
{
private readonly BehaviorSubject<T> bs;
public MyObject(BehvaiorSubject<T> externalSource)
{
this.bs = externalSource
}
public void DoSomething()
{
DoSomethingWith(bs.Value);
}
}
But using subjects directly seems to be frowned upon. But at least in this case I have the ability to use a readonly field to store the behaviorsubject.
The BehaviorSubject (or ReplaySubject) does seem like it was made for this purpose, but is there some other better way here? And if I should use the subject, would it make more sense to take the subject as an injected parameter, or take the original observable and build the subject locally in the constructor?
(by the way I'm aware about the need to deal with the 1st value if the source observable hasn't fired yet. Don't get hung up on that, that's not what I'm asking about)
I'd go with a generic solution utilizing the ReactiveUI library. RUI has a standard way of mapping IObservable<T> to an INotifyPropertyChanged stateful property.
public class ObservableToINPCObject<T> : ReactiveObject, IDisposable
{
ObservableAsPropertyHelper<T> _ValueHelper;
public T Value {
get { return _ValueHelper.Value; }
}
public ObservableToINPCObject(IObservable<T> source, T initial = default(T))
{
_ValueHelper = source.ToProperty(this, p=>p.Value, initial);
}
public Dispose(){
_ValueHelper.Dispose();
}
}
ValueHelper is contains both the current state of the observable and automatically triggers the correct INPC notification when the state changes. That's quite a bit of boiler plate handled for you.
and an extension method
public static class ObservableToINPCObject {
public static ObservableToINPCObject<T> ToINPC<T>
( this IObservable<T> source, T init = default(T) )
{
return new ObservableToINPCObject(source, init);
}
}
now given an
IObservable<int> observable;
you can do
var obj = observable.ToINPC(10);
and to get the latest value
Console.WriteLine(obj.Value);
also given that Value is an INPC supporting property you can use it in databinding. I use ToProperty all the time for exposing my observables as properties for WPF databinding.
To be Rx-ish I'd suggest avoiding the second option and go with your first, but modified in one of two ways.
Either (1) make your class disposable so that you can cleanly close off the subscription to the observables or (2) make a method that lets you clean up individual observables.
(1)
public class MyObject : IDisposable
{
private T CurrentT;
private IDisposable Subscription;
public MyObject(IObservable<T> externalSource)
{
Subscription = externalSource
.Subscribe((t) => { CurrentT = t; });
}
public void Dispose()
{
Subscription.Dispose();
}
public void DoSomething()
{
DoSomethingWith(CurrentT);
}
}
(2)
public class MyObject
{
private T CurrentT;
public IDisposable Observe(IObservable<T> externalSource)
{
return externalSource
.Subscribe((t) => { CurrentT = t; });
}
public void DoSomething()
{
DoSomethingWith(CurrentT);
}
}
Both allow proper clean-up and both don't use a subject.

Pass Action instead of hooking PropertyChanged?

In my current project I've faced the following situation:
VM1 is used to be shown on a screen.
VM1 has a public property of VM2.
VM1 has a public property of VM3.
VM3 has a propertry that depends on VM2.
VM1 has no disposing mechanism.
At the beginning I thought about hooking to VM2.PropertyChanged event to check for the property I want and change the VM3 affected property accordingly, as:
public class VM1 : INotifyPropertyChanged
{
public property VM2 VM2 { get; private set; }
public property VM3 VM3 { get; private set; }
public VM1()
{
this.VM2 = new VM2();
this.VM3 = new VM3();
this.VM2.PropertyChanged += this.VM2_PropertyChanged;
}
private void VM2_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// if e.PropertyName equals bla then VM3.SomeProperty = lol.
}
}
This means that, since I can not unhook the event in this class, I have a memory leak.
So I end up passing an Action to VM2 so that it will be called when its important property changes the value, as:
public class VM2 : INotifyPropertyChanged
{
public Action WhenP1Changes { get; set; }
private bool _p1;
public bool P1
{
get
{
return _p1;
}
set
{
_p1 = value;
this.WhenP1Changes();
this.PropertyChanged(this, new PropertChangedEventArgs("P1");
}
}
}
public class VM1 : INotifyPropertyChanged
{
public VM2 VM2 { get; private set; }
public VM3 VM3 { get; private set; }
public VM1()
{
this.VM2 = new VM2();
this.VM3 = new VM3();
this.VM2.WhenP1Changes = () => VM3.SomeProperty = "lol";
}
}
Do I have a memory leak here?
PD: It would be great if you can also answer to:
- Is this even a good practice?
Thanks
Do I have a memory leak here?
The lambda assigned to VM2.WhenP1Changes captures this VM1 instance (needed to access the VM3 property), so as long as the view model VM2 is alive, it will keep VM1 alive. Whether this ends up being a leak depends on the lifecycle of those view models, but the implications are effectively the same as your first example using events.
In short, I would prefer to use a delegate to notify between view models. If you have a parent view model which has access to the various child view models (it seems that you do), then you can use one or more delegates like events to notify each other when updates are required.
Rather than typing out the whole scenario again, I'd prefer to point you towards my answer to the Passing parameters between viewmodels question, which provides a full description and code examples of this technique.
There is also a further addition that may interest you that can be found in my answer to the If necessary, how to call functions in MainViewViewModel from other ViewModels question. Please let me know if you have any questions.

Save actions or funcs on secondary memory

I am creating a program where the user creates custom commands and execute them when needed. as a result I have a class similar to:
public class Command
{
Action c { get; set; }
// Overloaded Constructors------------------------------------
// changes the volume
public Command(int volumeChange)
{
c = ()=>
SomeClass.ChangeMasterVolume(volumeChange);
}
// Animate something
public Command(int x, int y)
{
c = ()=>
SomeClass.MoveMouse(x,y);
}
// etc.. there are more contructors....
//---------------------------------------------------------
public void ExecuteCommand()
{
c();
}
}
When the user closes the application I will like to save those commands somewhere on disk. There are about 200 different commands and it will be nice if I could serialize an instance from that class. Since it contains an Action it is not possible to serialize it.
It will be nice if I don't have to create a huge switch statement in order to determine what command to execute. What is the best way of dealing with this?
Sounds to me like you simply need to keep an interface around instead of a delegate.
public interface IDoThingy
{
void DoStuff();
}
public class IncreaseVolumeThingy : IDoThingy
{
public int Volume { get; set; }
public IncreaseVolumeThingy(int volume)
{
Volume = volume;
}
public void DoStuff()
{
SomeClass.ChangeMasterVolume(Volume);
}
}
public class Command
{
protected IDoThingy _thingy = null;
public Command(IDoThingy thingy)
{
_thingy = thingy;
}
public void ExecuteCommand()
{
_thingy.DoStuff();
}
}
So instead of creating a set of constructors, you simply make some form of factory based on the command specified. If the user is setting up a Increase volume command, then you new an instance of the IncreaseVolumeThingy and store it. When it is serialized, it can be recreated from state without a delegate.
Use reflection to call a class method by its name. Serialize the class and method name.
http://www.codeproject.com/Articles/19911/Dynamically-Invoke-A-Method-Given-Strings-with-Met

Categories