简体   繁体   中英

Calling a command in my ViewModel from a binding to an event in my XAML?

I am currently writing a Windows 8 application. I am trying to call a method in my ViewModel. I want this method to be called when an item is double clicked. I have defined the following DataTemplate in my XAML to do this:

<DataTemplate x:Key="ItemTemplate">
                <StackPanel Orientation="Horizontal">
                    <Image Width="185" Height="185" Stretch="Fill" Source="{Binding Path=Image}" DoubleTapped="{Binding Path=MethodIWishToBindTo}" IsDoubleTapEnabled="True"  />
                    </StackPanel>
            </DataTemplate>

The problem, of course, is the error message for my binding to MethodIWishToBindTo :

Invalid value for 'DoubleTapped'. Event values must be text

What is the best way for me to get around this ? I could call the method in the code-behind, however the method uses a property in my ViewModel, "SelectedItemInList" , which I don't believe can be accessed from the code behind.

Can anyone offer me some advice for this problem ?

Thanks a lot.

You could use Interactivity and a custom behavior to trigger the event. Here's a post that topically covers an example: MVVM-Light EventToCommand Behavior for CheckBox Checked/Unchecked in Silverlight

MVVM-Light definitely makes this easier, but it's possible without as well.

Here's an example of without: http://blog.roboblob.com/2010/01/26/binding-ui-events-from-view-to-commands-in-viewmodel-in-silverlight-4/

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