Event handling of ListBox selection

Dec 2, 2010 at 3:51 AM
Edited Dec 2, 2010 at 3:55 AM
I have a page with 2 user controls.


UserControl 1 has a list box with a list of data populated
UserControl 2 has text fields which will be populated based on selected item in UserControl1


I achieved this by attaching the event to the item of Listbox in the XAML
cal:Message.Attach="[Event MouseLeftButtonUp] = [Action Function($dataContext)]


The in the UserControl1 I implemented the Function; in the body I published an event with the message
        public void Function(ListBoundObject selectedIndexObject)
            EventAggregatorContainer.EventAggregator.Publish<MessageObject>(new MessageObject() { message = selectedIndexObject.message });

In the UserControl2's ModelView I subscribed to this event and populated the required fields


This works and I like the code except that I do not want to raise the event by writing code in the XAML. Is there any alternate way? If not is this the best way?


Again excuse if these are basic questions, I did not find such example anywhere. Also no harm in creating discussions which might work as references for others in future, i.e if I am correct in implementing this
Dec 2, 2010 at 9:21 AM

Message.Attach content is not exactly "code" (though it somewhat looks like that) but a syntax to facilitate the invocation of an action when an event is raised.
You might consider, however, using this alternative approach for the UserControl1 side, which doesn't involve any explicit message at all:


class UserControl1ViewModel {
        public BindableCollection<ListBoundObject> Items {get;set;}

	ListBoundObject _SelectedItem
	public ListBoundObject SelectedItem {
		get {return _SelectedItem;}
		set {
			_SelectedItem = value;
			 EventAggregatorContainer.EventAggregator.Publish<MessageObject>(new MessageObject() { message = _SelectedItem.message });

<ListBox ItemSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" ...>

You may also use a fully conventional approach, instead of explicit binding, with just:

<ListBox Name="Items" />