kikipoulet/SukiUI

[Doc] How to use SukiSideMenu.ItemsSource and SukiSideMenu.SelectedItem?

Closed this issue · 3 comments

Suggestion

I'm a beginner for AvaloniaUI based on MVVM. I'm trying to implement side menu function in my app following the example in document. This is my code <sukiUi:SukiSideMenu IsSearchEnabled="True" ItemsSource="{Binding MenuItems}" SelectedItem="{Binding SelectedPage}"> <sukiUi:SukiSideMenu.ItemTemplate> <DataTemplate> <sukiUi:SukiSideMenuItem Classes="Compact" Header="{Binding DisplayName}" PageContent="{Binding PageCont}"> </sukiUi:SukiSideMenuItem> </DataTemplate> </sukiUi:SukiSideMenu.ItemTemplate> </sukiUi:SukiSideMenu>
`namespace WikiPhoto.ViewModels
{

public class MainWindowViewModel : ViewModelBase
{

    public ObservableCollection<MenuItem> MenuItems { get; } = new()
    {
        new()
        {
            DisplayName = "Photo",
            PageCont = new PhotoView()
        },
        new()
        {
            DisplayName = "About",
            PageCont = new AboutView()
        }
    };

    public class MenuItem
    {
        public string DisplayName { get; set; }
        public UserControl PageCont { get; set; }
    }


    private ObservableCollection<string> _photo = new();

    public ObservableCollection<string> Photo
    {
        get => _photo;
        set
        {
            this.RaiseAndSetIfChanged(ref _photo, value);
        }
    }

    private MenuItem _selectedPage;
    
    public MenuItem SelectedPage
    {
        get => _selectedPage;
        set
        {
            this.RaiseAndSetIfChanged(ref _selectedPage, value);
            Console.WriteLine($"{SystemClock.UtcNow.Second}");
        }
    }
    
    public MainWindowViewModel()
    {
        Photo.Add("111111");
        SelectedPage = MenuItems[1];
    }
}

}`

Obviously it doesn't work. But when I read SukiUI.demo's implementation which is mentioned in the document, I felled puzzled, why the ItemSource is a collection of viewmodels? And how the navigation service works?

Additional Information

No response

OK, I have read the source code and changed to private ObservableCollection<SukiSideMenuItem> _menuItems;, then it works

New to Avalonia. Don't know C#.

Why does that work? Seems black-boxy and suggests documentation could use a touch-up.

Edit: e.g why must you use a specific data type for this, when as far as I could tell the Demo uses a readonly list of DemoPageBase.

The Demo implementation uses DI, making it easy to handle changes in the number of pages through reflection, which is mainly for managing multiple instances of Views.

You can also set up your own 'bindings' to Views (like DataContext or ViewLocator) and ViewModels. However, these implementations are beyond the scope of this documentation.