frostydog47
frostydog47

Reputation: 157

How do you bind MenuFlyout "itemsource" with collection when there are multiple flyouts on page?

I have a gridview with a flyout menu on each gridview item. This is complicated by that fact that I need to bind the ItemsSource of the each flyout menu to a collection. Since, menuflyout has no ItemsSource property by default, I have attempted to make use of Jerry Nixon’s solution posted here: Why doesn't the Windows 8.1 MenuFlyout have ItemsSource property?

Everything works fine the first time I click on a gridview item. However, when I click on another gridview item, I get the following error: “Element is already the child of another element.”

I’m guessing that Visual Studio is complaining because the flyout menu is already attached to the first grid item when I click on the next, and it’s attempting to reuse the data template. Can anyone help?

The XAML:

<GridView 
            ItemsSource="{x:Bind ViewModel.SourceForOfferorsList}"
                IsItemClickEnabled="True"
                IsTapEnabled="True"
                IsSwipeEnabled="False"
                CanDragItems="False"
                SelectionMode="Single"
                >
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="models:SetupCompany" >
                <Grid x:Name="MyGrid">
                    <FlyoutBase.AttachedFlyout>
                        <Flyout helpers:BindableFlyout.ItemsSource="{Binding ElementName=RankPage,Path=DataContext.SourceForSubfactorsFlyoutList,Mode=TwoWay}">
                            <helpers:BindableFlyout.ItemTemplate>
                                <DataTemplate>
                                    <MenuFlyoutItem Text="{Binding Text}" />
                                </DataTemplate>
                            </helpers:BindableFlyout.ItemTemplate>
                        </Flyout>
                    </FlyoutBase.AttachedFlyout>
                    <i:Interaction.Behaviors>
                        <core:EventTriggerBehavior EventName="Tapped">
                            <helpers:OpenFlyoutAction/>
                        </core:EventTriggerBehavior>

                    </i:Interaction.Behaviors>

                    <TextBlock Text="Hello"></TextBlock>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

The OpenFlyoutAction class:

    public object Execute(object sender, object parameter)
    {
        try
        {
            FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
        }
        catch (Exception e)
        {

            throw;
        }
        return null;
    }

The Bindable Flyout class:

public class BindableFlyout : DependencyObject
{
    #region ItemsSource

    public static IEnumerable GetItemsSource(DependencyObject obj)
    {

        return obj.GetValue(ItemsSourceProperty) as IEnumerable;


    }
    public static void SetItemsSource(DependencyObject obj, IEnumerable value)
    {

        obj.SetValue(ItemsSourceProperty, value);

    }
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.RegisterAttached("ItemsSource", typeof(IEnumerable),
        typeof(BindableFlyout), new PropertyMetadata(null, ItemsSourceChanged));
    private static void ItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    { Setup(d as Windows.UI.Xaml.Controls.Flyout); }

    #endregion

    #region ItemTemplate

    public static DataTemplate GetItemTemplate(DependencyObject obj)
    {
        return (DataTemplate)obj.GetValue(ItemTemplateProperty);
    }
    public static void SetItemTemplate(DependencyObject obj, DataTemplate value)
    {
        obj.SetValue(ItemTemplateProperty, value);
    }
    public static readonly DependencyProperty ItemTemplateProperty =
        DependencyProperty.RegisterAttached("ItemTemplate", typeof(DataTemplate),
        typeof(BindableFlyout), new PropertyMetadata(null, ItemsTemplateChanged));
    private static void ItemsTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    { Setup(d as Windows.UI.Xaml.Controls.Flyout); }

    #endregion

    private static async void Setup(Windows.UI.Xaml.Controls.Flyout m)
    {
        if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            return;
        var s = GetItemsSource(m);
        if (s == null)
            return;
        var t = GetItemTemplate(m);
        if (t == null)
            return;
        var c = new Windows.UI.Xaml.Controls.ItemsControl
        {
            ItemsSource = s,
            ItemTemplate = t,
        };
        var n = Windows.UI.Core.CoreDispatcherPriority.Normal;
        Windows.UI.Core.DispatchedHandler h = () => m.Content = c;
        await m.Dispatcher.RunAsync(n, h);
    }
}

Upvotes: 2

Views: 3203

Answers (1)

Xie Steven
Xie Steven

Reputation: 8591

I changed some places in your code and made a simple code sample for your reference:

<GridView x:Name="gridview"
            IsItemClickEnabled="True"
            IsTapEnabled="True"
            IsSwipeEnabled="False"
            CanDragItems="False"
            SelectionMode="Single">
        <GridView.ItemTemplate>
            <DataTemplate >
                <Grid x:Name="MyGrid">
                    <FlyoutBase.AttachedFlyout>
                        <Flyout local:BindableFlyout.ItemsSource="{Binding menuItems}">
                            <local:BindableFlyout.ItemTemplate>
                                <DataTemplate>
                                    <MenuFlyoutItem Text="{Binding Text}" />
                                </DataTemplate>
                            </local:BindableFlyout.ItemTemplate>
                        </Flyout>
                    </FlyoutBase.AttachedFlyout>
                    <TextBlock Text="{Binding item}"></TextBlock>
                    <i:Interaction.Behaviors>
                        <core:EventTriggerBehavior EventName="RightTapped">
                            <core:InvokeCommandAction Command="{Binding relayCommand}" CommandParameter="{Binding ElementName=MyGrid}"/>
                        </core:EventTriggerBehavior>
                    </i:Interaction.Behaviors>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        List<Test> ls = new List<Test>();
        List<MyMenuItem> myMenuItems = new List<MyMenuItem>();
        myMenuItems.Add(new MyMenuItem() {Text="menu1" });
        myMenuItems.Add(new MyMenuItem() {Text="menu2" });
        ls.Add(new Test() {item="item1",menuItems=myMenuItems });
        ls.Add(new Test() { item = "item2", menuItems = myMenuItems });
        gridview.ItemsSource = ls;
    }
}

public class Test:ViewModelBase
{
    public string item { get; set; }

    public List<MyMenuItem> menuItems { get; set; }

    public RelayCommand<object> relayCommand { get; set; }

    public Test()
    {
        relayCommand = new RelayCommand<object>(ShowFlyout);
    }

    private void ShowFlyout(object obj)
    {
        FrameworkElement senderElement = obj as FrameworkElement;
        FlyoutBase flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement);
        flyoutBase.ShowAt(senderElement);
    }
}

public class MyMenuItem
{
    public string Text { get; set; }
}

Upvotes: 1

Related Questions