I started using MVVM-Light with WPF yesterday 开发者_StackOverflowand it really makes a difference when it comes to structuring the code. But now i'm trying to figure out how to handle event.
Lets say I've got this view, with a TabControl. In every TabItem i have a ListBox. Now how do i handle the event SelectionChanged? And to mess things up, can i send the ListBox with the event as a parameter?
I'm very thankful for a simple code-sample.
In the case of selection changed events, it's better to use WPF built-in support for that: create an ICollectionView that wraps your collection, bind it to an ItemsControl (ListBox etc.) and the ICollectionView will have its CurrentItem automatically synchronized to the current selection. Of course, this only works for single selection.
For more complex events that you can't handle cleanly in a MVVM manner, it's always better to use the Messenger class in MVVM Light to send messages and have them caught by a listener; for example, the View can send a NotificationMessage and the ViewModel can register as a recipient with Messenger.Register
(I think it's called). It's a very extensible mechanism - you can also send an action (Action<>
or Func<>
or whatever) to be executed by the other side etc. etc.
These tips got me through two medium-sized LOB applications without a hitch.
If you want to do with MVVM approach more strictly (or hate to code in code-behind), EventToCommand can be another option. It's in the MVVM-light toolkit also.
In View(XAML), SelectedItem in listbox is served to ViewModel as below.
<ListBox Name="controlType" ItemsSource={Binding Path=items}>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand Command="{Binding Path=SelectControlType, Mode=OneWay}" CommandParameter="{Binding Path=SelectedItem, ElementName=controlType}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
In ViewModel, RelayCommand and a method receive the data as below.
public ICommand SelectControlType
{
get { return _selectControlType ?? (_selectControlType = new RelayCommand<object>(DoSomething)); }
}
// backing field.
private RelayCommand<object> _selectControlType;
// method to handle the data from SelectionChanged event
public void DoSomething(object param)
{
if(param is ValidItemType)
{
// Do somthing...
}
}
精彩评论