I am trying to translate WPF CodeBehid events like Event, Handler, EventSetter to MVVM pattern. I am not allowed to use System.Windows.Controls since I am using MVVM. And I am also avoiding 3rd party library to solve this issue.
Can somebody explain how to convert the following CodeBehind Event Handler to MVVM Event-Handler? Please explain as much as you can while writing answer.
XAML Code
<DataGridCheckBoxColumn Header="Select" Binding="{Binding Path=IsSelected}">
<DataGridCheckBoxColumn.CellStyle>
<Style TargetType="DataGridCell">
<EventSetter Event="MouseLeftButtonUp" Handler="ApprovedMouseUp"></EventSetter>
</Style>
</DataGridCheckBoxColumn.CellStyle>
</DataGridCheckBoxColumn>
Code Behind
private void ApprovedMouseUp(object sender, MouseButtonEventArgs e)
{
if(sender is DataGridCell)
{
var temp = (sender as DataGridCell).Content;
if(temp is CheckBox) (temp as CheckBox).IsChecked = !(temp as CheckBox).IsChecked;
}
}
There are few thumb rules regarding MVVM....
Models
andViewModles
should not referSystem.Windows.Controls
namespace.Models
andViewModles
should not handle events. UseICommand
interface for that.RoutedCommand
is not valid in Models / ViewModels (due to point 2). Hence use DelegateCommand /RelayCommand
Having said that, all the above points are perfectly allowed if you have written an Attached Behavior in MVVM.