You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If you migrate a WPF application and swap the using Galasoft.MvvmLight.CommandWpf; to using Microsoft.Toolkit.Mvvm.Input; all your commands using canExecute will stop working due to the specific handling of CommandManager missing in Windows Community Toolkit MVVM framework!
Reacted by Daniel Chalmers, Laurent Kempé, Luis Henrique, Luca Bonini, Vincent Wang, Brubning, Simone, Alfonso Andrés López Molina, saxmaster79 and Richard Bowater
My WPF sample doesn't use the CommandManager. It's something I always try to avoid. When I used the MvvmLight framework (long time ago) I only used the Galasoft.MvvmLight.Command not the Galasoft.MvvmLight.CommandWpf. Maybe because I had a Silverlight & UWP background. I never liked the WPF implementation.
Was this the workaround you did to get them to be enabled at the start of the application? In your scenario, you're just never dynamically changing their state of being able to be executed, eh?
Seems like an issue was a start to this type of discussion in the WPF repo here: dotnet/wpf#434
Could be worth filing a separate issue over there to formalize some sort of proposal specifically for a change to how CommandManager in WPF works to improve this experience to be more inline with how it's been simplified in UWP?
@dotMorten I know you've looked at the WPF codebase a bit. Do you have any good tips or know of good starting points for anyone who wanted to investigate this?
@michael-hawker I call the NotifyCanExecuteChanged from the ListViewEmployees_SelectionChanged events in WPF. It is not only about the Start of the app. It is necessary to detect ListView selection changes. The CommandParameter changes do not trigger the NotifyCanExecuteChanged in WPF.
In UWP the CanExecute is re-evaluated everytime the CommandParameter of a Button changes. WPF doesn't do this. So I had call the NotifyCanExecuteChanged manually. This is off course ugly. So I just updated my sample project. Introduced an NotifyCommandParameterChanges attached property for this. Not sure if this is the best property name though.
This is about raising CanExecuteChanged automatically, which is done in WPF by implementing ICommand and implementing the CanExcecuteChanged event like this:
So, the question is: how to hook up the CanExecuteChanged event of the ICommand implementation to automatically use CommandManager.RequerySuggested behind the scenes if used in a WPF app.
I think, by default it should not be hooked up, like it is now. Because CommandManager.RequerySuggested fires all the time when you click, press keys etc., which has a performance impact in bigger applications. It's always better to fire by hand when needed from a performance point of view, but means more work for a developer, also for smaller apps, where performance might not be different.
I suggest we find a way to turn this on with a single line of code at the application level. But as the CommandManager class is only available in WPF, there needs to be some extension to call into that WPF specific code.
Sometimes the CommandManager also does not find out when to invalidate (when you change ViewModel properties in code). Then you have to call the static CommandManager.InvalidateRequerySuggested() method to invalidate all commands in your app.
I'm looking at it right now, but I'm not sure if we should really implement that in the MVVM lib. I never used CommandManager in all the WPF apps in the past, but invalidated manually. But let's see what options we have.
Reacted by Rezwanur Rahman, CleanCodeDeveloper and Luis Henrique
@thomasclaudiushuber think something like @sonnemaf's helper attached property makes sense to have in one of our samples or are you thinking of something more specific than that? What have you done in the past when you "invalidated manually" in terms of the typical pattern?
@michael-hawker I don't think the issue is about the command parameter like described by @sonnemaf, I think it's about commands in general. In UWP/Silverlight etc., you have to raise the CanExecute manually. In WPF you can use an ICommand implementation that hooks up to CommandManager.RequerySuggested to raise it automatically on user input, like shown in the snippet in my comment above.
But I also didn't use CommandManager in WPF in the past 10 years (but before I did), as I found out that raising it manually is better for performance, and attaching directly to the static CommandManager.RequerySuggested event is also something to re-consider regarding memory leaks.
In one project we implemented an ICommand class that was able to retrieve property names to subscribe to these. I think something similar is also done in Prism's ICommand implementation, but I have to look that up. That would also be a great way to say at the Command level when it has to invalidate, and not having to call RaiseCanExecuteChanged at several property setters in your ViewModel. But it would still require more code for the developer than CommandManager, which "magically" just works for most cases.
attaching directly to the static CommandManager.RequerySuggested event is also something to re-consider regarding memory leaks.
I wasn't sure if this was meant as a re-consider in terms of doing this or not doing this? I think based on the past discussion you're saying it's better to handle manually to avoid memory leaks compared to trying to hook into the events of the CommandManager.RequerySuggested? Or are you saying that you're thinking of re-considering now and that it may be better to leverage the CommandManager.RequerySuggested to avoid accidental memory leaks from trying to manage it manually?
If the former (avoiding CommandManager.RequerySuggested), do you think if we have a solid WPF example in our sample repo of how to best manage this manually or with some light-weight helper that'd be enough? Then we could potentially show folks how to get better performance in their apps and avoid the issue?
@michael-hawker Sorry for my not so precise sentence. It was meant as a re-consider of not doing this.
I think based on the past discussion you're saying it's better to handle manually to avoid memory leaks compared to trying to hook into the events of the CommandManager.RequerySuggested?
Yes, exactly.
If the former (avoiding CommandManager.RequerySuggested), do you think if we have a solid WPF example in our sample repo of how to best manage this manually or with some light-weight helper that'd be enough? Then we could potentially show folks how to get better performance in their apps and avoid the issue?
I think this is a great idea, and I'm happy to help out there.
I've actually been a bit behind on getting PRs reviewed there. ☹ We have a Uno one which is close which splits the ViewModels out to .NET Standard projects (as they should be) here: #16 and then a Xamarin PR based off of that one: #33
Let me start working on getting those reviewed (there's some build failures I should bubble-up), but if you wanted to get started, feel free to fork off of #33 or just start tinkering with some thoughts in this space that we could integrate later. Whatever works best for you! 🎉
After talking to @Sergio0694 we're just going to provide some guidance in our Samples/Docs. I'm going to move that to that repo for tracking over there.
@IngoBleile what are you referring to? If you mean a fix for this extension, as I mentioned that's just a gist I put together as a proof of concept, you're free to take it and modify it with the suggestions above to make it work for you. If you meant a fix to make this all work out of the box on WPF, that's not planned due to the MVVM Toolkit being cross platform by design 🙂
Yes, I know that looks heavy for a command predicate, but it's at the main menu when nothing else is happening, and it works fine when triggered by CommandManager.RequerySuggested.
I would like to remove all of my personally coded MVVM stuff and only use the Community Toolkit, but I rely on these change notifications. My app runs on modern hardware, so I'm not worried about having to run a few extra CanExecute checks.
Maybe what I'll do is keep a collection of IRelayCommand objects in my base class, subscribe to CommandManager.RequerySuggested, and pass on the notifications. My base class is already IDisposable, so there won't be a concern about leaking references.
I'd really like to use the source generators. I guess that means I'd need to use reflection since I wouldn't be able to know the IRelayCommand objects otherwise.
I've come across this issue, and I understand I need to call NotifyCanExecuteChanged manually for each command in the relevant property setters, but I just want to double check I've understood fully before I commit to working on these changes.
This is how the commands are declared:
///Uses PropertyChanged.Fody to inject NotifyPropertyChanged
public string SomeValue { get; set; }
private ICommand addCmd;
public ICommand AddCmd => this.addCmd ?? (this.addCmd = new RelayCommand(() =>
{
//Do some stuff
}, this.AddRecordCmd_CanExecute));
private bool AddCmd_CanExecute()
{
return this.SomeValue == "Foo";
}
Since NotifyCanExecuteChanged isn't a part of ICommand interface I need to change my ICommand to RelayCommand and also convert my auto property to a full property so that I can call NotifyCanExecuteChanged(), like this:
///Uses PropertyChanged.Fody to inject NotifyPropertyChanged
private string someValue;
public string SomeValue
{
get => this.someValue;
set
{
this.someValue= value;
this.AddCmd.NotifyCanExecuteChanged();
}
}
private ICommand addCmd;
public ICommand AddCmd => this.addCmd ?? (this.addCmd = new RelayCommand(() =>
{
//Do some stuff
}, this.AddRecordCmd_CanExecute));
private bool AddCmd_CanExecute()
{
return this.SomeValue == "Foo";
}
Is this correct?
Changing from ICommand to RelayCommand is easy enough, it's having to update all the properties used in CanExecute methods that's unpleasant with how many commands there are and each one having to be done by hand (rather than a nice easy Replace job).
Side note: it's disappointing that the Migrating from Mvvmlight article doesn't mention this breaking change at all. :(
Reacted by Laurent Kempé, Toemsel, Antoine-Ali Zarrouk, Antik Mozib, Luis Henrique and Richard Bowater
No worries! 🙂 And yeah, we can't do that because that'd require the use of CommandManager, which is WPF-specific unfortunately.
Hello @Sergio0694 , you guys are obviously free to handle things how you see fit, but would you say MAUI, for example, is not cross platform due to it allowing you to tweak platform specific things? Personally I would say that having support for command re-query for WPF is something that many developers have use for and it takes away from the added benefit of the library. If we were talking about some obscure feature I would understand, but this seems as sort of a core functionality on one of the platforms.
You'd have to do this on each type that exposes IRelayCommand properties, but you could wrap it up as a utility method that you just call from the constructor after the properties are initialized.
Beware when creating a utility method for this because RequerySuggested only keeps a weak reference to the handler, so unless you keep a strong reference to each object's handler elsewhere, your handler will mysteriously not work. I did it like so:
publicstaticclassRelayCommandHelpers{privatestaticList<EventHandler>handlers=new();publicstaticvoidRegisterCommandsWithCommandManager(objectcontainer){voidHandler(object?s,EventArgse){foreach(varcommandincontainer.GetType().GetProperties().Where(p =>p.PropertyType.IsAssignableTo(typeof(IRelayCommand))).Select(p =>(IRelayCommand?)p.GetValue(container))){command?.NotifyCanExecuteChanged();}}// We have to retain a reference to the handler because RequerySuggested// only keeps a weak reference to it.handlers.Add(Handler);CommandManager.RequerySuggested+=Handler;}}
Edit2: A more performant implementation which assumes that your IRelayCommand properties don't change:
Activity
michael-hawker commentedon Nov 20, 2020
@Sergio0694 @jamesmcroft opening this here for tracking from the comment @laurentkempe raised in the sample repo and on Twitter: https://twitter.com/laurentkempe/status/1327707975532810243
@sonnemaf I know you wrote a WPF sample a while back here: https://github.com/sonnemaf/ToolkitMvvmDemo - Is this something you encountered as well or did you not have the same setup for this scenario?
@deanchalk I know you may have done some early poking with WPF as well?
sonnemaf commentedon Nov 20, 2020
My WPF sample doesn't use the CommandManager. It's something I always try to avoid. When I used the MvvmLight framework (long time ago) I only used the Galasoft.MvvmLight.Command not the Galasoft.MvvmLight.CommandWpf. Maybe because I had a Silverlight & UWP background. I never liked the WPF implementation.
Can't help you with this one, sorry.
laurentkempe commentedon Nov 20, 2020
Yeah, this problem is only a WPF one!
michael-hawker commentedon Dec 1, 2020
@sonnemaf I saw here that you called the
NotifyCanExecuteChangeddirectly:Was this the workaround you did to get them to be enabled at the start of the application? In your scenario, you're just never dynamically changing their state of being able to be executed, eh?
michael-hawker commentedon Dec 1, 2020
Seems like an issue was a start to this type of discussion in the WPF repo here: dotnet/wpf#434
Could be worth filing a separate issue over there to formalize some sort of proposal specifically for a change to how
CommandManagerin WPF works to improve this experience to be more inline with how it's been simplified in UWP?@dotMorten I know you've looked at the WPF codebase a bit. Do you have any good tips or know of good starting points for anyone who wanted to investigate this?
dotMorten commentedon Dec 1, 2020
@michael-hawker Sorry no I haven't dug into that part of WPF. But my blogpost here might be helpful: https://xaml.dev/post/Compiling-and-debugging-WPF
sonnemaf commentedon Dec 2, 2020
@michael-hawker I call the NotifyCanExecuteChanged from the ListViewEmployees_SelectionChanged events in WPF. It is not only about the Start of the app. It is necessary to detect ListView selection changes. The CommandParameter changes do not trigger the
NotifyCanExecuteChangedin WPF.The CommandParameter of the RaiseSalary and Delete buttons are databound to the SelectedItem of the ListBox.
The Commands of my ViewModel have a CanExecute which is dependent of the passed Employee parameter.
In UWP the CanExecute is re-evaluated everytime the CommandParameter of a Button changes. WPF doesn't do this. So I had call the
NotifyCanExecuteChangedmanually. This is off course ugly. So I just updated my sample project. Introduced an NotifyCommandParameterChanges attached property for this. Not sure if this is the best property name though.Does this answer your question?
thomasclaudiushuber commentedon Dec 4, 2020
This is about raising CanExecuteChanged automatically, which is done in WPF by implementing ICommand and implementing the CanExcecuteChanged event like this:
The CommandManager.RequerySuggested is fired whenever an input event happens that might invalidate commands. It's described here: https://docs.microsoft.com/en-us/dotnet/api/system.windows.input.commandmanager.requerysuggested?view=net-5.0
So, the question is: how to hook up the CanExecuteChanged event of the ICommand implementation to automatically use CommandManager.RequerySuggested behind the scenes if used in a WPF app.
I think, by default it should not be hooked up, like it is now. Because CommandManager.RequerySuggested fires all the time when you click, press keys etc., which has a performance impact in bigger applications. It's always better to fire by hand when needed from a performance point of view, but means more work for a developer, also for smaller apps, where performance might not be different.
I suggest we find a way to turn this on with a single line of code at the application level. But as the CommandManager class is only available in WPF, there needs to be some extension to call into that WPF specific code.
Sometimes the CommandManager also does not find out when to invalidate (when you change ViewModel properties in code). Then you have to call the static CommandManager.InvalidateRequerySuggested() method to invalidate all commands in your app.
I'm looking at it right now, but I'm not sure if we should really implement that in the MVVM lib. I never used CommandManager in all the WPF apps in the past, but invalidated manually. But let's see what options we have.
michael-hawker commentedon Dec 4, 2020
Thanks for the extra insights @sonnemaf and @thomasclaudiushuber. Makes a lot more sense now.
@thomasclaudiushuber think something like @sonnemaf's helper attached property makes sense to have in one of our samples or are you thinking of something more specific than that? What have you done in the past when you "invalidated manually" in terms of the typical pattern?
thomasclaudiushuber commentedon Dec 4, 2020
@michael-hawker I don't think the issue is about the command parameter like described by @sonnemaf, I think it's about commands in general. In UWP/Silverlight etc., you have to raise the CanExecute manually. In WPF you can use an ICommand implementation that hooks up to CommandManager.RequerySuggested to raise it automatically on user input, like shown in the snippet in my comment above.
But I also didn't use CommandManager in WPF in the past 10 years (but before I did), as I found out that raising it manually is better for performance, and attaching directly to the static CommandManager.RequerySuggested event is also something to re-consider regarding memory leaks.
In one project we implemented an ICommand class that was able to retrieve property names to subscribe to these. I think something similar is also done in Prism's ICommand implementation, but I have to look that up. That would also be a great way to say at the Command level when it has to invalidate, and not having to call RaiseCanExecuteChanged at several property setters in your ViewModel. But it would still require more code for the developer than CommandManager, which "magically" just works for most cases.
michael-hawker commentedon Dec 4, 2020
Thanks @thomasclaudiushuber.
I wasn't sure if this was meant as a re-consider in terms of doing this or not doing this? I think based on the past discussion you're saying it's better to handle manually to avoid memory leaks compared to trying to hook into the events of the CommandManager.RequerySuggested? Or are you saying that you're thinking of re-considering now and that it may be better to leverage the CommandManager.RequerySuggested to avoid accidental memory leaks from trying to manage it manually?
If the former (avoiding CommandManager.RequerySuggested), do you think if we have a solid WPF example in our sample repo of how to best manage this manually or with some light-weight helper that'd be enough? Then we could potentially show folks how to get better performance in their apps and avoid the issue?
thomasclaudiushuber commentedon Dec 4, 2020
@michael-hawker Sorry for my not so precise sentence. It was meant as a re-consider of not doing this.
Yes, exactly.
I think this is a great idea, and I'm happy to help out there.
michael-hawker commentedon Dec 4, 2020
@thomasclaudiushuber that'd be great. We haven't started an official WPF sample in our MVVM Toolkit Sample Repo.
I've actually been a bit behind on getting PRs reviewed there. ☹ We have a Uno one which is close which splits the ViewModels out to .NET Standard projects (as they should be) here: #16 and then a Xamarin PR based off of that one: #33
Let me start working on getting those reviewed (there's some build failures I should bubble-up), but if you wanted to get started, feel free to fork off of #33 or just start tinkering with some thoughts in this space that we could integrate later. Whatever works best for you! 🎉
michael-hawker commentedon Mar 2, 2021
After talking to @Sergio0694 we're just going to provide some guidance in our Samples/Docs. I'm going to move that to that repo for tracking over there.
13 remaining items
Sergio0694 commentedon Feb 15, 2022
@IngoBleile what are you referring to? If you mean a fix for this extension, as I mentioned that's just a gist I put together as a proof of concept, you're free to take it and modify it with the suggestions above to make it work for you. If you meant a fix to make this all work out of the box on WPF, that's not planned due to the MVVM Toolkit being cross platform by design 🙂
IngoBleile commentedon Feb 15, 2022
@Sergio0694 Yes, I meant to make it work for WPF out of the box. Sorry, I missed the point of being cross platform! :)
Sergio0694 commentedon Feb 15, 2022
No worries! 🙂
And yeah, we can't do that because that'd require the use of
CommandManager, which is WPF-specific unfortunately.fix: call NotifyCanExecuteChanged explicity CommunityToolkit/MVVM-Sam…
jamiehankins commentedon Feb 23, 2023
This is a surprise to me. I tried using your RelayCommand objects and all of my commands with predicates stopped working.
Having to manually trigger checks is a no go when I have conditions like this:
Yes, I know that looks heavy for a command predicate, but it's at the main menu when nothing else is happening, and it works fine when triggered by
CommandManager.RequerySuggested.I would like to remove all of my personally coded MVVM stuff and only use the Community Toolkit, but I rely on these change notifications. My app runs on modern hardware, so I'm not worried about having to run a few extra CanExecute checks.
This is how my implementation handles it:
Maybe what I'll do is keep a collection of IRelayCommand objects in my base class, subscribe to
CommandManager.RequerySuggested, and pass on the notifications. My base class is already IDisposable, so there won't be a concern about leaking references.I'd really like to use the source generators. I guess that means I'd need to use reflection since I wouldn't be able to know the IRelayCommand objects otherwise.
will-scc commentedon Feb 28, 2023
I've come across this issue, and I understand I need to call NotifyCanExecuteChanged manually for each command in the relevant property setters, but I just want to double check I've understood fully before I commit to working on these changes.
This is how the commands are declared:
Since
NotifyCanExecuteChangedisn't a part ofICommandinterface I need to change myICommandtoRelayCommandand also convert my auto property to a full property so that I can callNotifyCanExecuteChanged(), like this:Is this correct?
Changing from ICommand to RelayCommand is easy enough, it's having to update all the properties used in
CanExecutemethods that's unpleasant with how many commands there are and each one having to be done by hand (rather than a nice easy Replace job).Side note: it's disappointing that the Migrating from Mvvmlight article doesn't mention this breaking change at all. :(
Fully solved #7
Fully solved #7
Fully solved #7
Fully solved #7
Fully solved #7
Fully solved #7
pikausp commentedon Jul 15, 2024
Hello @Sergio0694 , you guys are obviously free to handle things how you see fit, but would you say MAUI, for example, is not cross platform due to it allowing you to tweak platform specific things? Personally I would say that having support for command re-query for WPF is something that many developers have use for and it takes away from the added benefit of the library. If we were talking about some obscure feature I would understand, but this seems as sort of a core functionality on one of the platforms.
Just a food for thought :)
doxxx commentedon Aug 20, 2024
Another alternative solution is to call
NotifyCanExecuteChangedonIRelayCommands whenCommandManager.RequerySuggestedis raised:You'd have to do this on each type that exposes
IRelayCommandproperties, but you could wrap it up as a utility method that you just call from the constructor after the properties are initialized.Beware when creating a utility method for this because
RequerySuggestedonly keeps a weak reference to the handler, so unless you keep a strong reference to each object's handler elsewhere, your handler will mysteriously not work. I did it like so:Edit2: A more performant implementation which assumes that your
IRelayCommandproperties don't change:Edit3: Use weak references for the
IRelayCommandsto avoid memory leaks in case views are being created dynamically.doxxx commentedon Aug 20, 2024
I created a gist for this helper: https://gist.github.com/doxxx/911ba2af9847362e12e01a045273184e