|
I have been having this problem lately where when I bind a button to a command, the CanExecute only every fires once - on startup. So the condition is never reevaluated.
Here's my code:
The button
<controls:FlatButton Style="{StaticResource FlatButtonStyle}"
Caption="Edit"
Description="Edit the selected address"
ImageSource="/UI.WPF;component/Media/Images/edit.png"
Command="{Binding Path=EditAddressCommand}"/>
Code behind
private ICommand _EditAddressCommand;
public ICommand EditAddressCommand
{
get
{
if (_EditAddressCommand == null)
_EditAddressCommand = new RelayCommand(editAddress, editAddressCanExecute);
return _EditAddressCommand;
}
}
and
private bool editAddressCanExecute()
{
return SelectedAddress != null;
}
private void editAddress()
{
... code here
}
The SelectedAddress IS being set, I checked it. editAddressCanExecute only ever fires once - on startup.
Seems sort of vague, but I really don't know how to debug this. I get no output errors or other errors of any kind.
If it's not broken, fix it until it is
|
|
|
|
|
* are you changing the DataContext?
* are you stomping over _EditAddressCommand?
* when the canExecute "stops working", does the execute still work?
* you can try turn on verbose debugging. Tools | Options | Debugging | Output Window. Set all the WPF traces to "ALL".
|
|
|
|
|
The ICommand interface has 3 Members. Beside the Execute and CanExecute methods, there is also a CanExecuteChanged event. You should raise this event when one of the conditions of CanExecute has changed.
|
|
|
|
|
Uh... no you shouldn't. That event is raised when the value of CanExecute has changed. You don't raise it yourself. There is no need anyways. The framework queries the commands in response to system events like mouse clicks, focus changes, etc.
|
|
|
|
|
I'm starting to doubt now. I have read about it in a book about MVVM pattern (Applied WPF 4 in Context, Raffaelle Garofalo, Apress, 2011, ch.8). The ICommand interface is used to build a custom RelayCommand, which should compensate for some lacks in the standard WPF commands. A part of the implementation is the use of the CanExecuteChanged event.
It works great. The CanExecute changes exactly when my ViewModel wants it to change it and the View reacts to it. I agree that I cases like mouse events and focus changes you just don't want to interfere with the commands. I'm not sure if it will work or should be avoided to take control of the CanExecuteChanges event in other situations.
|
|
|
|
|
RelayCommand and RelayCommand<T> are for the MVVM pattern. The sole purpose is to allow for the execute / canExecute handlers to be held in the command object itself (and thus the VM) rather then requiring a Window with a command pool. As I mentioned in my response to Pete, only ButtonBase and MenuItem even use it (or so it appears). There are other events that cause the commands to be requeried. I have NEVER come across a case where the standard RelayCommand did not work.
|
|
|
|
|
Martijn is correct. Most custom command implementations don't automatically raise the event, preferring the developer raise it at appropriate points. It's only recently that Laurent Bugnion has started to offer this in MVVM Light, for instance.
|
|
|
|
|
Funny . I have used the standard RelayCommand and RelayCommand<T> implementations which don't raise the event and all my UI's work just fine . The standard implementation overrides the subscription as such:
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}
but it does nothing to raise the event itself.
In fact, if you look at the .Net source... the only object that is even using the CanExecuteChanged event appears to be ButtonBase and MenuItem.
|
|
|
|
|
I have found an example of an ICommand implementation using this same standard implementation (CommandManger.RequerySuggested). At this moment I don't know how the CommandManager works.
This weekend I'll give it a try. It's allways good to look at alternatives.
The custom implementation of the RelayCommand I'm using uses listeners. They listen to the PropertyChanged events of properties of the ViewModel. And when changes are detected the CanExecuteChanged of the Command is triggered.
|
|
|
|
|
Wow... that really sounds like overkill . I did actually think of a scenario where the standard RelayCommand implementation doesn't work as expected. If you have a window with a background worker that goes 0 to 100 or whatever... when it is done, the commands aren't refreshed until the user interacts with the UI. The workaround for that scenario has typically been to add a call to CommandManager.InvalidateRequerySuggested(). I'm not sure how you are wiring everything up with your implementation, but I guess that solves that problem without the CommandManager.InvalidateRequerySuggested() call. Personally, the CommandManager.InvalidateRequerySuggested() seems cleaner to me .
|
|
|
|
|
The CommandManager does work indeed, as you already knew . And would do the trick with probably all viewmodels I have writen.
The CommandManager raises the CanExecuteChanged quite often, probably with every user interaction which might change the data of the viewmodel. Although one might not notice a difference in performance.
The code I'm using is a little more complicated, but declaring the command is only a little more complicated. Although one might forget to add a listener when the CanExecute conditions change.
DummySave = new MvvmCommand(p => DoSave(p), p => (!string.IsNullOrEmpty(LastName) && !string.IsNullOrEmpty(FirstName))).
AddListener<TestViewModel>(this, vm => vm.LastName).
AddListener<TestViewModel>(this, vm => vm.FirstName);
|
|
|
|
|
I've seen more than a few examples that just subscribe to the event, and don't worry about the CommandManager. For instance, if you look at the DelegateCommand that was supplied by the P and P team, you'll see that this doesn't raise it by default. The reason for this is simple - quite often you want to control whether or not the execute change notification is raised because you could be updating several properties in one go and you don't want this to be handled until after you have raised all of the changes.
I use a variation of this to put the control into the developers hand, whereby they can specify on the implementation of the command whether or not they want to automatically subscribe.
|
|
|
|
|
Lets say you change 100 props on object X. Ok, so you'd be able to say "save the updates til later"... So you'd either send 100 property updates now or later. Not much difference in overhead. More of an overhead when you are dealing with collections, then it makes sense to batch updates (sometimes).
|
|
|
|
|
The reason for saving the updates normally relates to applications which absolutely rely on updates happening in a particular sequence, a common requirement in financial systems or geospatial systems where you want the update to trigger after a particular point.
And don't blame me on this - this is the implementation you get from the likes of DelegateCommand from the Patterns and Practices team.
|
|
|
|
|
This is the answer I would have given. Well done and my 5.
|
|
|
|
|
Ok, I'm still stuck on this. My RelayCommand class (That I got from Josh Smith) defines
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
The event declaration appears in intellisense, but not the RaiseCanExecuteChanged. Maybe this is why I'm having the problem.
I wrote a quick sample app[^] that demonstrates what is happening.
Thing is, I'v been using this RelayCommand forever, and now all of a sudden I start having this problem.
[UPDATE]
I replaced my class with this[^] and now it works. It seems I was using a Func instead of a Predicate. I know for sure this was working code at some point.
If it's not broken, fix it until it is
modified 31-Jul-12 17:09pm.
|
|
|
|
|
Yes you are right. Get my +5.
http://www.exploresilverlight.com
Cheers!
Vinod
|
|
|
|
|
I have a very basic query. Let's say we have a Color1, and I need Color2 to be
Color.FromRgb (Math.Min(Color1.R+10,255), Math.Min(Color1.G+10,255), Math.Min(Color1.B+10,255));
But I am not able to do this simple thing. Basically, I've got stuck with integer and byte conversion. Please suggest in following code-
private Color GetNewColor(Color colorParameter)
{
Color newColor;
return newColor;
}
|
|
|
|
|
What exactly is going wrong? Are you getting an exception or a compiler error or is it just not doing what you expect?
One possible issue I can see is an overflow of the colour component. For example, with a byte , if you add 10 to 255 you'll actually end up with 9, and Math.Min won't work as you expect. You can catch this problem by surrounding the code with a checked statement, which will cause the runtime to throw on an overflow.
The quickest solution to this would be to cast the byte to an int first, do the addition, and cast the result back to a byte (once you're certain it'll fit).
|
|
|
|
|
Thanks for the reply!
Problem was with casting only. I've sorted that out now. Trivial, but just thought of sharing it:
byte r = Convert.ToByte(Math.Min(255, Color1.R + 10));
byte g = Convert.ToByte(Math.Min(255, Color1.G + 10));
byte b = Convert.ToByte(Math.Min(255, Color1.B + 10));
return Color.FromRgb(r, g, b);
|
|
|
|
|
In Silverlight you can do this:
private Color GetNewColor(Color colorParameter)
{
Color newColor;
Color newcolor = Color.FromArgb(0, 255, 10, 10);
return newColor;
}
You can read this[^] too.
Regards
Christian Amado
MCITP | MCTS | MOS | MTA
Olimpia ☆ ★★★
Please mark as answer, if it helps.
|
|
|
|
|
Hi,
Below is my requirement:
I need to display various data in my dashboard report. the data will be fetched from SQL server 2005 DB. the data will be like:
1. sales data: buy, sell, value, sales team code & name
2. client asset data: product, asset value, sales team code & name, client code & name
3. revenue data: brokerage amount, product and client code & name
need to send all the above data to silverlight page through single WCF service. what is the best method to achieve the requirement.
any advise would be very helpful and i am new to wcf and silverlight.
thanks in advance
Durga Charan K
|
|
|
|
|
Use a placeholder class that contains all these as getter-setter properties.
You can share this property class (or model) between the server and client OR have two copies and populate them both on server and client. That choice is left to you.
|
|
|
|
|
I have a Silverlight Business Application, three project on it:
1. SLApp (Silverlight Application).
2. SLDataServices (ADO.NET Entity Framework, Domain Service, Metadata, Extensions for metadata).
3. SLWeb (ASp.NET WebSite with ASP.NET Membership enabled and working).
When I run the project a Login Page appears, you type user and pass. After that you logged on, so the Silverlight app loads (I pass user & pass parameter) and login in silverlight app too.
When the Ribbon Menu loads (via DomainDataSource) I see the error on the RequiredAuthentication Atributte on my DomainService in SLDataServices project. When I breakpointed on this line of code I can see that I have a cookie empty and the ServiceContext setted to null.
Using an Oracle Database.
How can I obtain the user authenticated on my DomainService?
Thanks in advance.
Christian Amado
MCITP | MCTS | MOS | MTA
Olimpia ☆ ★★★
Please mark as answer, if it helps.
|
|
|
|
|
I need to get color value, when user clicks anywhere (inside or ourside of the main window). Possible? If yes -
1) How do I get pixel value of outside of window? How can I check the MouseDown/Up in this case?
2) What should be the approach to get color value of a pixel, which is outside of the main window?
|
|
|
|