Automatically select an item from populated combobox with binding? Silverlight
Lets say i have the following two controls.
<ListBox ItemsSource="{Binding Path=Events}"
DisplayMemberPath="Name"
SelectedItem="{Binding SelectedEvent, Mode=TwoWay}"
Grid.Column="0" Grid.RowSp开发者_开发问答an="4" Margin="5"/>
and
<ComboBox x:Name="VenueBox"
ItemsSource="{Binding Path=VenueNames}"
SelectedItem="{Binding Path=SelectedVenueName, Mode=TwoWay}"
Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2"
Margin="10"/>
The ListBox is bound to an ObservableCollection which "holds" a custom class. The ComboBox is bound to an ObservableCollection of strings. Now the custom class has a string property which values are from the combobox. The thing i want is if i select an item in the ListBox, then automatically select that value from the ComboBox. Is it possible with pure XAML or some action in code behind is a must? I hope my explanation is clear, thank you for your help.
If you can afford to bind the SelectedItem
of the ComboBox differently (having a dedicated property seems superfluous anyway since you already have SelectedEvent
) this should do it:
SelectedItem="{Binding Path=SelectedEvent.Venue, Mode=TwoWay}"
(I don't know the actual name of the venue property so that might need to be adjusted to your model)
I'm going to read between the lines here. You have a "Event" class which represents some event. Events occur at some date and time and a location which we are calling a "Venue", the "Event" class has a string property which is the name of the venue.
You also have a list of possible venue names.
The object you are binding to has SelectedEvent
property of type "Event" and a SelectedVenue
property of type string
. The rule you wish to apply is that when a Event is chosen in the list box the SelectedVenue
can only be the venue specified by the event.
So the real question is: where does the enforcement of this rule belong?
This is not really the job of the view to apply. The model to which you are binding should be aware of this rule. Code in the SelectedEvent
property setter should ensure the correct value of SelectedVenue
is applied.
The View will then simply reflect the current state of the model but it is the model's responsibility to understand what "correct" state is not the view's.
精彩评论