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

后端 未结 4 685
栀梦
栀梦 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条回答
  •  旧时难觅i
    2020-12-01 05:15

    This is a bit of a hack, but it works well and allows you to use commands and avoid code behind. This also has the added benefit of not triggering the command when you double-click (or whatever your trigger is) in the empty ScrollView area assuming your ListBoxItems don't fill the entire container.

    Basically, just create a DataTemplate for your ListBox that is composed of a TextBlock and bind the width of the TextBlock to the width of the ListBox, set the margins and padding to 0, and disable horizontal scrolling (because the TextBlock will bleed beyond the visible bounds of the ScrollView triggering the horizontal scroll bar otherwise). The only bug I've found is that the command won't fire if the user clicks precisely on the border of the ListBoxItem, which I can live with.

    Here is an example:

    
        
            
                
                    
                        
                    
                
            
        
    
    

提交回复
热议问题