binding an ICommand to a custom eventhandler
I am trying to create a datapager usercontrol. This user control has one event declared in its code behind :
public event EventHandler OnPageIndexPagerChanged;
I use this control in a main usercontrol, and I bind my event to another event in the code behind like this :
xaml :
OnPageIndexPagerChanged="SuperDataPager_OnPageIndexPagerChanged"
c# (Code behind) :
private void SuperDataPager_OnPageIndexPagerChanged(object sender, EventArgs e)
{
var viewModel = DataContext as ViewSchedeConsuntiviViewModel;
if (viewModel != null)
{
viewModel.FilterCommand.Execute(sender);
}
}
And this works fine, But I would have liked to skip passing through the code behind an do something like :
OnPageIndexPagerChanged="{Binding Path=FilterCommand}"
This, I already do for the filter button, present in my main usercontrol, therefore I thought I could do the same for this event. But every time I receive an error :
Impossibile assegnare alla proprietà 'Super.Silverlight.SuperDataPager.OnPageIndexPagerChanged'. [Line: 90 Position: 55]
'iexplore.exe' (Silverlight): Loaded 'C:\Program Files (x86)\Microsoft Silverlight\4.0.60531.0\it\mscorlib.resources.dll' su System.Windows.Application.LoadComponent(Object component, Uri resourceLocator) su Super.Silverlight.SchedeConsuntivi.InitializeComponent() su Super.Silverlight.SchedeConsuntivi..ctor()
Sorry for the error in Italian, but I was unable to get t开发者_如何学编程he exact translation -> (unable to assign property...)
Could someone explain me this behavior?
Thanks for reading,
[EDIT] Here is the my view Model for the main usercontrol :
public class MyViewModel : DependencyObject, INotifyPropertyChanged
{
public ICommand FilterCommand { get; set; }
public MyViewModel()
{
FilterCommand = new Super.Silverlight.Tools.DelegateCommand<object>(p => Filter());
}
public void Filter()
{
//....blah blah blah...
}
}
[/EDIT]
First of all your Event is not a RoutedEvent, something you should consider. But thats not the main problem.
Of course you can't set an ICommand to an EventHandler. Don't get confused of RoutedEvents with RoutedCommands. You have 2 options, you can give your UserControl an dependency Property of type ICommand and just fire that inside your code behind. In XAML you can bind now your command. Or if you want to have that as an event, again consider using RoutedEvents, there are options to bind commands to routedevents like EventBehaviorFactory and some more.
The easiest solution would be to use an ICommand directly in you user control and remove the event.
I'm afraid you can not do this, cause Command is special type routed event, instead reading DataPager specification doesn't seems to support any commanding. And what you do in code, instead, is assign to event.
EDIT
You can have also workarrounds but it will not definitely like you want here.
Regards.
精彩评论