How to Toggle Navigation Drawer Via MVVM Command in .NET MAUI?
This article explains how to toggle the .NET MAUI Navigation Drawer using MVVM
commands in an application. Using commands instead of event handlers enhances modularity, testability, and maintains a clean separation between UI and logic.
ViewModel
Define a ViewModel with a property to track the drawer’s state and a command to toggle it:
public class MainPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private bool _isDrawerOpen;
public bool IsDrawerOpen
{
get => _isDrawerOpen;
set
{
_isDrawerOpen = value;
OnPropertyChanged(nameof(IsDrawerOpen));
}
}
public ICommand ToggleDrawerCommand { get; }
public MainPageViewModel()
{
ToggleDrawerCommand = new Command(ToggleDrawer);
}
private void ToggleDrawer()
{
IsDrawerOpen = !IsDrawerOpen;
}
}
Setting the BindingContext
Ensure that the ViewModel is set as the BindingContext of the page:
<ContentPage.BindingContext>
<local:MainPageViewModel/>
</ContentPage.BindingContext>
XAML
Bind the IsOpen property of NavigationDrawer to IsDrawerOpen
and the toggle command to an ImageButton:
<navigationdrawer:SfNavigationDrawer x:Name="navigationDrawer" IsOpen="{Binding IsDrawerOpen, Mode=TwoWay}">
<navigationdrawer:SfNavigationDrawer.ContentView>
<Grid x:Name="mainContentView" BackgroundColor="White" RowDefinitions="Auto,*">
<HorizontalStackLayout BackgroundColor="#6750A4" Spacing="10" Padding="5,0,0,0">
<ImageButton x:Name="hamburgerButton"
Source="hamburgericon.png"
Command="{Binding ToggleDrawerCommand}"/>
</HorizontalStackLayout>
</Grid>
</navigationdrawer:SfNavigationDrawer.ContentView>
</navigationdrawer:SfNavigationDrawer>
By following these steps, you can toggle the Navigation Drawer using an MVVM command instead of event handlers, resulting in a more modular and testable application.
Output
Download the complete sample from GitHub
Conclusion
I hope you enjoyed learning how to toggle the Navigation Drawer via MVVM command in .NET MAUI.
You can refer to our .NET MAUI Navigation Drawer feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started with configuration specifications.
You can check out our components from the License and Downloads page for current customers. If you are new to Syncfusion®, try our 30-day free trial to check out our other controls.
Please let us know in the comments section below if you have any queries or require clarification. You can also contact us through our Support Forums, Direct-Trac, or Feedback Portal. We are always happy to assist you!