Reputation: 8759
I have a ComboBox in a Silverlight application that uses databinding to change its visibility based on a property value in the ViewModel. Here is the ComboBox XAML:
<ComboBox x:Name="Combo1" ...
Visibility="{Binding MyProperty, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}">
... Some hard coded ComboBoxItems ...
</ComboBox>
BooleanToVisibilityConverter
is a converter class that converts a Boolean value to the appropriate Visibility value to show/hide the ComboBox.
This works great, however what I'd like to be able to do is whenever the ComboBox becomes visible I want to select the first item. So if a user selects an item from the ComboBox then manipulates the form so that the ComboBox is hidden, then later makes changes that redisplays the ComboBox, I want the ComboBox to show the first item not the user-selected item.
Thanks!
Upvotes: 0
Views: 493
Reputation: 8882
This is a classic scenario where the MVVM pattern would help you out, as opposed to using a converter. Your view model could contain a Visibility property which would be data bound to your ComboBox's Visible property. Then in the setter of the bound Visibility property (on your view model) you could invoke a method on your view model that selected the first item in your ComboBox. Here's an example of what this could look like: How can you get a XAML TextBlock in WP7 Silverlight to collapse when it contains no data?
The collection that your ComboBox is bound to, along with the ComboBox's selected item could also be on your view model and hooked to your view via data binding, thus allowing everything to take place in your view model, as well as setting yourself up nicely to unit test the behavior you're looking for.
Upvotes: 1