WPF: How to bind a command to the ListBoxItem using MVVM?

后端 未结 4 676
栀梦
栀梦 2020-12-01 04:53

I have just started learning MVVM. I\'ve made the application from scratch by following this MVVM tutorial (I highly recommend it to all MVVM beginners out there). Basically

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 05:13

    This is made tricky because of the DoubleClick event. There are a few ways to do this:

    1. Handle the double-click event in code behind, and then manually invoke a command/method on your ViewModel
    2. Use an attached behavior to route the DoubleClick event to your Command
    3. Use a Blend Behavior to map the DoubleClick event to your command

    2 and 3 might be more pure, but frankly, 1 is easier, less complex, and not the worst thing in the world. For a one-off case, I'd probably use approach #1.

    Now, if you changed your requirements to use, say, a hyperlink on each item, it would be easier. Start out by naming the root element in your XAML - e.g., for a Window:

    
    

    Now, in the DataTemplate for your ListBox items, use something like this:

    
      
        
          
    

    The ElementName binding lets you resolve the OpenEntryCmd from the context of your ViewModel, rather than the specific data item.

提交回复
热议问题