views:

236

answers:

1

Hi,

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)?

A: 

Hi,

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

LBugnion
Hi, apparently the code for the EventToCommand didn't show in my post. I use the EventToCommand in the following way: <command:EventToCommand Command="{Binding SelectedProductionCommand}" CommandParameter="{Binding SelectedItem, ElementName=loadProductionAutoCompleteBox}" PassEventArgsToCommand="True" /> I'm not really following the suggestion you made to get around this issue (the TwoWay binding on a VM Property). Can you please elaborate? Btw, do you have any comment regarding the comment I made on my Post (regarding sending <Object> inststead of <MyItem>). Is this bad practise?
JAS
Sorry for the bad formatting, it seems like all linebreaks is disregarded in comments! :/
JAS
Hi, I edited my answer because some signs had been swallowed. Hope it makes more sense now. Regarding the twoway binding, what don't you understand? Simply define a property in the VM and set a TwoWay data binding between the TextBox.Text property and the VM property you just defined. If you don't understand, please send me an email.Cheers,Laurent
LBugnion