简体   繁体   中英

How to bind UI Controls event to ViewModel(MVVM)?

I have AutoCompleteBox in my application and I have binded its ItemSource/SelectedItem property to ViewModel.

Now I want to bind event and I am not getting the way to bind AutoCompeletBox KeyUP/KeyDown event with ViewModel how do i acheive it??

I have a Button in application and I have used RelayCommand to bind Command of that Button(It's Working).

Can you please give me details exaple of binding?

If you are using the GalaSoft MVVM toolkit, you can use EventToCommand to bind the KeyUp event to a command. Check it out here - http://geekswithblogs.net/lbugnion/archive/2009/11/05/mvvm-light-toolkit-v3-alpha-2-eventtocommand-behavior.aspx

You might also want to change the UpdateSourceTrigger property in the binding expression of the auto-complete box to "Property Changed"

Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"

The default binding behavior is on LostFocus, so this will update your ViewModel instantly.

KeyUp / KeyDown event handling should be part of View implementation. Then you can create logic in View, that will use binding or commands to get related values for autocompletion from or to ViewModel.

And before any purist, who thinks all logic should be in VM starts downvoting. I believe logic, that is bound to View should stay in View.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM