开发者

Error handling for AutoCompleteBox with Silverlight 3 + MVVM Light toolkit

开发者 https://www.devze.com 2023-01-02 11:52 出处:网络
I\'m trying to create a UserControl that contains a AutoCompleteBox. I want to use the SelectedItem property of this AutoCompleteBox to populate other UserControls with information based on which item

I'm trying to create a UserControl that contains a AutoCompleteBox. I want to use the SelectedItem property of this AutoCompleteBox to populate other UserControls with information based on which item the User selected. To prevent the SelectedItem to be fired every time a user "navigate" between items in the drop-down I've created a EventToCommand that executes on DropDownClosed event like this:

The command is of type: public RelayCommand SelectedItemCommand { get; private set; }

This works fine except for when a user start typing something that has a match at the beginning, but if the user continue typing and there is no match anymore, then the DropDown is closed and no item is actually selected. This gives me an error that says:

Unable to cast object of type 'System.Windows.RoutedPropertyChangedEventArgs`1[System.Boolean]' to type 'MyProject.ViewModels.MyItem'

I tried to make a try-catch statement in the Command method for the command, but the exception seems to be fired even before I get into that method.

My question is: How can I prevent the command from beeing fired if there is no-match (that is, no actual SelectedItem in the AutoCompleteBox)?开发者_高级运维


Are you using PassEventArgsToCommand? In that case, the RelayCommand must be RelayCommand<EventArgs> and the CommandParameter may not be used. It is a limitation of the ICommand interface, which can only have one CommandParameter. Annoying, I know, but usually I am able to use a different way to get what I want (for example by binding the SelectedItem to a property on my VM with a TwoWay binding).

Let me know, Laurent

0

精彩评论

暂无评论...
验证码 换一张
取 消