Antyos
Antyos

Reputation: 545

Binding a Static Generic Class in XAML

I'm trying to implement a generic version of the MenuExtension class found on this post: https://stackoverflow.com/a/33841544/3721066. The MenuExtension class works fine when the MenuFlyoutItem type in question is explicitly defined, however, I would like to be able to use the class for lists of MenuFlyoutItems, RadioMenuFlyoutItems, etc. without having to define a version for each type.

So far, I have a generic version of Romasz's MenuExtension

public static class MenuExtension<T> where T : MenuFlyoutItemBase
{
    public static List<T> GetMyItems(DependencyObject obj)
    { return (List<T>)obj.GetValue(MyItemsProperty); }

    public static void SetMyItems(DependencyObject obj, List<T> value)
    { obj.SetValue(MyItemsProperty, value); }

    public static readonly DependencyProperty MyItemsProperty =
        DependencyProperty.Register("MyItems", typeof(List<T>), typeof(MenuFlyoutItemExtension<T>),
        new PropertyMetadata(new List<T>(), (sender, e) =>
        {
            Debug.WriteLine("Filling collection");
            var menu = sender as MenuFlyoutSubItem;
            menu.Items.Clear();
            foreach (var item in e.NewValue as List<T>) menu.Items.Add(item);
        }));
}

Here's the XAML code to that uses it (Which works when using the original version of MenuExtension)

        <Button.ContextFlyout>
                <MenuFlyout>
                    <MenuFlyoutItem Text="An Item" />
                    <MenuFlyoutSubItem
                        Text="Sub menu"
                        local:MenuExtension.MyItems="{x:Bind local:GradeWeightsFlyoutItems.GetMenuItems(_currItem)}"/>
                </MenuFlyout>
        </Button.ContextFlyout>

I have no idea how the local:MenuExtension.MyItems works in this context, so that likely is part of it.

And just in case, here's the C# function that gets the menu items:

    static class GradeWeightsFlyoutItems
    {
        public static List<MenuFlyoutItem> GetMenuItems(Grade grade)
        {
            return  grade.weights.Select(weight =>
                    {
                        var flyout = new MenuFlyoutItem
                        {
                            Text = weight.Name,
                        };
                        // Other code here left out for simplicity
                        return flyout;
                    }).ToList();
        }
    }

Upvotes: 0

Views: 254

Answers (1)

mm8
mm8

Reputation: 169370

I am afraid generics aren't supported in XAML: https://github.com/microsoft/microsoft-ui-xaml/issues/931.

If you want to be able to set your attached property to different type of collections and sequences, you could change List<T> to IEnumerable.

Upvotes: 1

Related Questions