Bind Context Menu inside ItemsControl?

前端 未结 2 467
太阳男子
太阳男子 2021-01-03 10:21

How can I add a ContextMenu to a ItemsControl, where:

  • The ItemsSource of the ItemsControl is in the ViewModel of the UserControl holding the ItemsControl
相关标签:
2条回答
  • 2021-01-03 10:31

    Firstly, just check your parameter values for null:

    return parameter == null ? false : _canExecuteMethod((T)parameter); 
    

    Secondly, this is the old ContextMenu.DataContext problem: The ContextMenu is displayed in a different visual tree to the rest of the UI. It therefore has no access to a DataContext from the main UI visual tree. Because of this, we have to use a little trick to pass it through to the other visual tree. Our connection between the two is the ContextMenu.PlacementTarget property.

    From the linked page, this property

    Gets or sets the UIElement relative to which the ContextMenu is positioned when it opens.

    We can use the Tag property of the ContextMenu.PlacementTarget object to pass the DataContext. Basically, just set the Tag property on the object that you will set the ContextMenu on. Try something like this:

    <ItemsControl x:Name="myItems" ItemsSource="{Binding MyItems}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding MyText}" Tag="{Binding DataContext, 
                    RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" 
                    ContextMenu="{StaticResource ItemContextMenu}" />
            </DataTemplate>                    
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    ...

    <ContextMenu x:Key="ItemContextMenu" ItemsSource="{Binding ContextMenuItems}" 
        ItemContainerStyle="{StaticResource CommandMenuItemStyle}"
        DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"/>
    

    That's it. Now the UI elements declared in the ContextMenu will have access to whatever object you data bind to the Tag property. There's absolutely no need for EventSetters to use a ContextMenu... it's quite simple if you know how.

    0 讨论(0)
  • 2021-01-03 10:49

    It is a known bug in wpf and framework 4.0 try using 4.5 framework. https://connect.microsoft.com/VisualStudio/feedback/details/619658/wpf-virtualized-control-disconnecteditem-reference-when-datacontext-switch

    0 讨论(0)
提交回复
热议问题