Category Archives: PRISM

Prism.Commands.DelegateCommand

Just a quick one on how to use the DelegateCommand that comes with PRSIM libraries. The name space for this command is  Prism.Commands. The following usage shows how to use the command with and without command parameter.

Most of the time we use only the Command so we can declare it as following in our viewmodel which will be bound to view:

public ICommand NormalCommand
{
get
{
return new DelegateCommand(() =>
{
MessageBox.Show(“Hello World without command parameter”);
});
}
}

 

when we need the command parameter we can use the same syntax but with a generic parameter for lambda expression:

public ICommand ParameterisedCommand
{
get
{
return new DelegateCommand<string>((s) =>
{
MessageBox.Show(“Hello world with parameter :  ” + s);
});
}
}

In the above usage, we have used a string as the generic parameter because we expect the parameter of the type string, however if we expect the parameter of any complex type then we can use object in the generic parameter and then typecast it to the required type.

Advertisements

Exception: ItemsControl is inconsistent with its items source

This can get tricky if you don’t realise where its arising from.

I had one listbox with its ItemsSource Binding set to List<T> in viewmodel. Via a command, i was updating the listbox items source. Now it was fine until I added a new item to the list and fired RaisePropertyChanged() somewhere in the middle of the code for Command execution.

What happens now is that UI is asked to refresh its state before Command execution is complete. i.e. UI finds its ItemSource collection different to one on the source(ViewModel property) because the Source property on ViewModel is now increased with one additional item but UI still is hanging around with one less item in list!

The best way to resolve this was to use ObservableCollection<> so there won’t be any need for change notification. However, in principle, this error can be avoided if UI is asked refresh only after the command execution(or whatever process is updating the source collection) is done. This requires use of dispatcher.

_dispatcherService.Dispatch(() => RaisePropertyChanged(nameof(Employees)))

I have injected _dispatcherService in my class so just calling it but in essence this will defer the UI refresh until its safe to do so i.e. after current processing is over