views:

2644

answers:

2

For those doing pure MVVM, how do you handle a ComboBox SelectionChanged event without reverting to code behind?

I tried e.g. AttachedBehaviors but Event="SelectedChanged" is not supported:

<ComboBox>
    <ComboBoxItem Content="Test1">
        <c:CommandBehaviorCollection.Behaviors>
            <c:BehaviorBinding Event="SelectionChanged" 
                               Command="{Binding SelectedChanged}"
                               CommandParameter="MainBorder123"/>
        </c:CommandBehaviorCollection.Behaviors>
    </ComboBoxItem>
    <ComboBoxItem Content="Test2"/>
    <ComboBoxItem Content="Test3"/>
</ComboBox>
+1  A: 

You would use a data trigger to trigger an event on a different UI element such as "enable / disable, or visible /invisible"

If you want the selected element to show the object data in other UI elements then you would use data binding and set the datacontext of the UI data display elements to be bound to the currently selected item in the combo box.

Peter
ok, I could do that if all I want to do is change the XAML, but what if I want to e.g. use a comboxbox to execute code that does something that XAML cannot do, e.g. load a new resource file and attach it to the current window? or e.g. change some data in the database, etc.
Edward Tanguay
Then you could use a binding your View Model to the combo box SelectionChanged.I'm not sure where you would look for an example but Karl Shifflet and Josh Smith are the two main blogs I go to for MVVM help the links to their blogs are below.http://karlshifflett.wordpress.com/2009/06/03/troubleshooting-silverlight-3-broken-bindings/http://joshsmithonwpf.wordpress.com/2009/05/20/device-specific-interaction-logic-in-an-mvvm-application/Sorry I can't help more on the specifics, i'm fairly new to WPF and MVVM myself.
Peter
oops forgot to mention Karl Shifflet has been doing a lot of WPF Line OF Business events, look on his blog for them, they contain some excellent powerpoint examples and code samples also.
Peter
+3  A: 

I'm not sure if what you're after is possible, but the way I do it is to simply bind the SelectedItem to a property on view model. Then within the property setter, I call any custom code that I want to happen i.e. setting other properties based on rule. If I need the selected item to be bound to an object aswell (for other bound controls to update) I set this in the setter too and send out a notification.

HAdes