SelectionChanged ListBox connect to ViewModel class

Create class PerformActionHelper

 public static class PerformActionHelper
 {
     public static void PerformAction(Window view, Action action) where TViewModel : class
     {
         try
         {
             if (view.DataContext is TViewModel vm) action?.Invoke(vm);
         }
         catch (Exception) { return; }
     }
 }

Create event in XAML Code: SelectionChanged="ListBox_SideMenu_SelectionChanged" In MainWindow.cs at this:

  private void ListBox_SideMenu_SelectionChanged(object? sender, SelectionChangedEventArgs e)
  {
      PerformActionHelper.PerformAction(this, vm => vm.MenuIndexChange());
  }

Create MenuIndexChange in ViewModel (is DataContext)

 internal void MenuIndexChange()
 {
     switch (SelectedMenuIndex)
     {
         case 0:
             break;
         case 1:
             break;
         case 2:
             break;
         case 3:
             break;
         case 4:
             break;
         default:
             break;
     }
 }
 

Post a Comment

Previous Post Next Post