Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 195141
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T16:39:20+00:00 2026-05-11T16:39:20+00:00

I have the following GridView : <ListView Name=TrackListView ItemContainerStyle={StaticResource itemstyle}> <ListView.View> <GridView> <GridViewColumn Header=Title

  • 0

I have the following GridView:

<ListView Name="TrackListView" ItemContainerStyle="{StaticResource itemstyle}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Title" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Name}"/>
            <GridViewColumn Header="Artist" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Artist.Name}" />
            <GridViewColumn Header="Album" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Name}"/>
            <GridViewColumn Header="Length" Width="100" HeaderTemplate="{StaticResource BlueHeader}"/>
        </GridView>
     </ListView.View>
</ListView>

Now I would like to display a context menu on a right click on a bounded item that will allow me to retrieve the item selected when I handle the event in the code behind.

In what possible way can I accomplish this?


[Update]

Following Dennis Roche‘s code, I now have this:

    <ListView Name="TrackListView" ItemContainerStyle="{StaticResource itemstyle}">
        <ListView.ItemContainerStyle>
            <Style TargetType="{x:Type ListViewItem}">
                <EventSetter Event="PreviewMouseLeftButtonDown" Handler="OnListViewItem_PreviewMouseLeftButtonDown" />
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu>
                            <MenuItem Header="Add to Playlist"></MenuItem>
                        </ContextMenu>
                     </Setter.Value>
                </Setter>
            </Style>
        </ListView.ItemContainerStyle>

        <ListView.View>
            <GridView>
                <GridViewColumn Header="Title" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Name}"/>
                <GridViewColumn Header="Artist" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Artist.Name}" />
                <GridViewColumn Header="Album" Width="100" HeaderTemplate="{StaticResource BlueHeader}" DisplayMemberBinding="{Binding Album.Name}"/>
                <GridViewColumn Header="Length" Width="100" HeaderTemplate="{StaticResource BlueHeader}"/>
            </GridView>
         </ListView.View>
    </ListView>

But upon running, I am receiving this exception:

Cannot add content of type
‘System.Windows.Controls.ContextMenu’
to an object of type ‘System.Object’.
Error at object
‘System.Windows.Controls.ContextMenu’
in markup file
‘MusicRepo_Importer;component/controls/trackgridcontrol.xaml’.

What is the problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T16:39:20+00:00Added an answer on May 11, 2026 at 4:39 pm

    Yes, add a ListView.ItemContainerStyle with the Context Menu.

    <ListView>
      <ListView.Resources>
        <ContextMenu x:Key="ItemContextMenu">
          ...
        </ContextMenu>
      </ListView.Resources>
      <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
          <EventSetter Event="PreviewMouseLeftButtonDown" Handler="OnListViewItem_PreviewMouseLeftButtonDown" />
          <Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}"/>
        </Style>
      </ListView.ItemContainerStyle>
    </ListView>
    

    NOTE: You need to reference the ContextMenu as a resource and cannot define it locally.

    This will enable the context menu for the entire row. 🙂

    Also see that I handle the PreviewMouseLeftButtonDown event so I can ensure the item is focused (and is the currently selected item when you query the ListView). I found that I had to this when changing focus between applications, this may not be true in your case.

    Updated

    In the code behind file you need to walk-up the visual tree to find the list container item as the original source of the event can be an element of the item template (e.g. a stackpanel).

    void OnListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      if (e.Handled)
        return;
    
      ListViewItem item = MyVisualTreeHelper.FindParent<ListViewItem>((DependencyObject)e.OriginalSource);
      if (item == null)
        return;
    
      if (item.Focusable && !item.IsFocused)
        item.Focus();
    }
    

    The MyVisualTreeHelper that is use a wrapper that I’ve written to quickly walk the visual tree. A subset is posted below.

    public static class MyVisualTreeHelper
    {
      static bool AlwaysTrue<T>(T obj) { return true; }
    
      /// <summary>
      /// Finds a parent of a given item on the visual tree. If the element is a ContentElement or FrameworkElement 
      /// it will use the logical tree to jump the gap.
      /// If not matching item can be found, a null reference is returned.
      /// </summary>
      /// <typeparam name="T">The type of the element to be found</typeparam>
      /// <param name="child">A direct or indirect child of the wanted item.</param>
      /// <returns>The first parent item that matches the submitted type parameter. If not matching item can be found, a null reference is returned.</returns>
      public static T FindParent<T>(DependencyObject child) where T : DependencyObject
      {
        return FindParent<T>(child, AlwaysTrue<T>);
      }
    
      public static T FindParent<T>(DependencyObject child, Predicate<T> predicate) where T : DependencyObject
      {
        DependencyObject parent = GetParent(child);
        if (parent == null)
          return null;
    
        // check if the parent matches the type and predicate we're looking for
        if ((parent is T) && (predicate((T)parent)))
          return parent as T;
        else
          return FindParent<T>(parent);
      }
    
      static DependencyObject GetParent(DependencyObject child)
      {
        DependencyObject parent = null;
        if (child is Visual || child is Visual3D)
          parent = VisualTreeHelper.GetParent(child);
    
        // if fails to find a parent via the visual tree, try to logical tree.
        return parent ?? LogicalTreeHelper.GetParent(child);
      }
    }
    

    I hope this additional information helps.

    Dennis

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following ListView : <ListView Name=TrackListView> <ListView.View> <GridView> <GridViewColumn Header=Title Width=100 HeaderTemplate={StaticResource
I have a ListView with the following code: <ListView Name=ListView1> <ListView.View> <GridView> <GridViewColumn Header=File
I have the following: <ListView Name="lstStepTargets" Margin="0,3,0,-3" VerticalAlignment="Stretch" > <ListView.View> <GridView> <GridViewColumn Header="Enabled" >
Let's say I have the following ListView: <ListView ScrollViewer.VerticalScrollBarVisibility=Auto> <ListView.View> <GridView> <GridViewColumn Header=Something DisplayMemberBinding={Binding
I have the following code in xaml: <ListView Name=listView1 IsSynchronizedWithCurrentItem=True > <ListView.View> <GridView> <GridViewColumn
I have the follwoing listview in my xaml: <ListView Name=listView1> <ListView.View> <GridView> <GridViewColumn Width=Auto
I have the following code: <ListView Name=lvwYears Margin=0,32,191,29 ItemsSource={Binding Path=YearCollection}> <ListView.View> <GridView> <GridViewColumn> <GridViewColumnHeader>
I have the following ListView: <ListView Name=listView> <ListView.View> <GridView> <GridView.ColumnHeaderContainerStyle> <Style TargetType={x:Type GridViewColumnHeader}> <Setter
I have the following XAML: <GridView x:Key=myGridView> <GridViewColumn CellTemplate={StaticResource myTemplate}/> </GridView> <DataTemplate x:Key=myTemplate> <ContentPresenter
I have following WPF ListView: <ListView Grid.Column=2 Grid.Row=1 Margin=0,53,12,6 Name=lvwProperties ItemsSource={Binding Path=SelectedPropertyItems, Mode=TwoWay} Grid.ColumnSpan=2>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.