How to Navigate to different page in avalonia UI using Community Toolkit MVVM package
Asked Answered
E

1

6

I have created a project using Avalonia UI MVVM C# project. and I am very new to this. I am using the Community Toolkit MVVM package, not the Reactive UI package. There are two pages, "MainWindow" and "SettingWindow". There is a button on the "MainWindow" page. Once the user clicks that button, user should be navigated to the "Settings" page. How can I accomplish this using the Community Toolkit MVVM package in Avalonia UI?

MainWindow codebehind

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext= new MainWindowViewModel();
        }
    }

MainWindow viewModel Code

[INotifyPropertyChanged]
    public partial class MainWindowViewModel
    {
        [ObservableProperty]
        public string greeting = "Welcome to Avalonia!";

        [RelayCommand]
        public void GotoSettings()
        {
          //navigate to setting window
        }
    }

SettingWindow codebehind

 public partial class SettingWindow : Window
        {
            public SettingWindow()
            {
                InitializeComponent();
                DataContext = new SettingWindowViewModel();
            }
        }

SettingWindow ViewModel code

[INotifyPropertyChanged]
public partial class SettingWindowViewModel
{
    public string greeting => "setting page";
}
Earsplitting answered 15/1, 2023 at 17:31 Comment(0)
B
0

You can add contentpresenter type controls and bind the content property inside the MainWindowModel, but I do it in a way that might not be pure in MVVM architecture as your main window viewmodel will know your setting window view. I created a property with class type like UserControl or derived View class. Then you can change that observable property to your setting window view class via commands in the codes, and you can also pass in the view model of that new page during these stages.

Edit: The original answer is anti-pattern. Try to utilize the out-of-the-box solution from Avalonia, like the view locator class that implements the IDataTemplate interface, and resolve the views by this class. Or abstract the business logic into an interface, and implement the UI part in that service instead.

Bearer answered 6/12, 2023 at 2:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.