ContextMenu disappears immediately after appearing - c#

I have a context menu but it is disappearing instantly after it shows up.
<TextBlock Name="InputtedAddress" Text="{Binding Path=InputtedAddress}" MouseDown="InputtedAddress_MouseDown"/>
System.Windows.Controls.ContextMenu thisMenu;
private void InputtedAddress_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
thisMenu = new System.Windows.Controls.ContextMenu();
MenuItem thisMenuItem = new MenuItem() { Header = "Zoom to Incident" };
thisMenuItem.Click += new RoutedEventHandler(thisMenuItem_Click);
thisMenu.Items.Add(thisMenuItem);
thisMenu.IsOpen = true;
}
}

It's likely because you're not marking the MouseDown event to handled. Set e.Handled to true and it will no longer propagate and your ContextMenu will stay open.
That said, this is an awful way to assign a ContextMenu in the first place. Why not just do this:
<TextBlock ...>
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Zoom to Incident" Click="thisMenuItem_Click"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>

You should assign your menu to the ContextMenu property of your TextBlock so that the opening and positioning will be taken care of for you. You also don't need to create the menu in each MouseDown; just create it once and assign it to the ContextMenu property.
In XAML:
<TextBlock
Name="InputtedAddress"
Text="{Binding Path=InputtedAddress}"
>
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem
Header="Zoom to Incident"
Click="ContextMenu_Click"
/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
If you do want to show it manually you will need to position it before showing it by setting the PlacementTarget property, something like this:
private void InputtedAddress_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
thisMenuPlacementTarget = InputtedAddress;
thisMenu.IsOpen = true;
}
}
P.S. "Inputted" is not a word :)

Related

How to enable menuitems on a ContextMenu - WPF

I'm trying to create a ContextMenu on a UserControl derived object. Note: This is NOT a WinForms App, it is pure WPF.
So I create the ContextMenu thus:
<UserControl.Resources>
<ContextMenu x:Key="cmLCD_CopyCutPaste">
<MenuItem Name="CutOption" Header="{x:Static p:Resources.Popup_Cut}" Command="Cut" Click="MenuItem_Cut" IsEnabled="True"/>
<MenuItem Name="CopyOption" Header="{x:Static p:Resources.Popup_Copy}" Command="Copy" Click="MenuItem_Copy" IsEnabled="True"/>
<MenuItem Name="PasteOption" Header="{x:Static p:Resources.Popup_Paste}" Command="Paste" Click="MenuItem_Paste" IsEnabled="True"/>
</ContextMenu>
</UserControl.Resources>
The mousebutton event is setup thus:
d:DesignHeight="66" d:DesignWidth="340" Focusable="True" KeyDown="Grid_KeyDown" MouseRightButtonDown="EMS_UI_LCDscreen_MouseRightButtonDown" >
In the code behind, the constructor starts like this:
public EMS_UI_LCDscreen()
{
InitializeComponent();
// Find the ContextMenu created on this object - it is called cmLCD_CopyCutPaste
ContextMenu cm = FindResource("cmLCD_CopyCutPaste") as ContextMenu;
// If we found the contextMenu, assign it the ContextMenu placeholder for this instance.
if (cm != null)
{
ContextMenu = cm;
}
...
The mouse click(right button) is handled like this:
private void EMS_UI_LCDscreen_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
if (this.ContextMenu is ContextMenu cm)
{
if (cm != null)
{
if (DataContext is DeviceEditorData ded)
{
cm.DataContext = ded.Device.GetStructuredLocation(0);
cm.IsEnabled = true;
cm.PlacementTarget = sender as Button;
cm.IsOpen = true;
}
}
}
}
There are the three event handlers to actually respond to the user selection on the ContextMenu:
private void MenuItem_Cut(object sender, RoutedEventArgs e)
{
}
private void MenuItem_Copy(object sender, RoutedEventArgs e)
{
}
private void MenuItem_Paste(object sender, RoutedEventArgs e)
{
}
View of the ContextMenu being shown on the LCD Image component
The component I have created appears in a few different contexts, but the one I'm mainly interested in is inside of a DataGrid that shows various items of data, each with one of these components. when right clicked, the component faithfully displays the popup context menu as expected..... BUT all the items on the menu are grayed out and basically not enabled.
So my question is, what is the missing piece of glue that effectively enables the menu items so that they can be clicked to do the required actions. Most of the answers already seen on the net go into detail of how to do it in a WinForms app, but despite hours of searching, I can find no clear solution to what should be a very simple task of enabling the menu items.
Can some kind soul please put me out of my anguish and in a few lines of code show me how to do it! Thank you
UPDATE: This is the XAML implementation for the LCD Component:
<UserControl x:Class="EMS_Config_Tool.UIComponents.WPF.EMS_UI_LCDscreen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:p="clr-namespace:EMS_Config_Tool.Properties"
mc:Ignorable="d"
d:DesignHeight="66" d:DesignWidth="340" Focusable="True" KeyDown="Grid_KeyDown" MouseRightButtonDown="EMS_UI_LCDscreen_MouseRightButtonDown" >
<UserControl.Resources>
<ContextMenu x:Key="cmLCD_CopyCutPaste">
<MenuItem Name="CutOption" Header="{x:Static p:Resources.Popup_Cut}" Command="{Binding Cut}"/>
<MenuItem Name="CopyOption" Header="{x:Static p:Resources.Popup_Copy}" Command="{Binding Copy}"/>
<MenuItem Name="PasteOption" Header="{x:Static p:Resources.Popup_Paste}" Command="{Binding Paste}"/>
</ContextMenu>
</UserControl.Resources>
<UserControl.CommandBindings>
<CommandBinding Command="Cut"
CanExecute="CutCommand_CanExecute"
Executed="CutCommand_Executed" />
<CommandBinding Command="Copy"
CanExecute="CopyCommand_CanExecute"
Executed="CopyCommand_Executed" />
<CommandBinding Command="Paste"
CanExecute="PasteCommand_CanExecute"
Executed="PasteCommand_Executed" />
</UserControl.CommandBindings>
</UserControl>
As can be seen, it is very simple - there are no items added to the control - it only serves as a Canvas upon which the code behind draws all the needed items which are purely graphic "draw" items.
This is the implementations of the 6 methods referenced, in the corresponding .cs file for the xaml above:
private void CutCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
// Verify relevant conditions and set CanExecuteRoutedEventArgs.CanExecute accordingly
e.CanExecute = true;
}
private void CutCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
// Execute the command action
if (sender is EMS_UI_LCDscreen lcd)
{
if (TheDevice != null)
{
Clipboard.SetDataObject(TheDevice.GetStructuredLocation(0).ToString());
TheDevice.SetLocation(0, "");
lcd.StructuredTextToShow = TheDevice.GetStructuredLocation(0);
}
else
{
Clipboard.SetDataObject(lcd.StructuredTextToShow.ToString());
lcd.StructuredTextToShow.SetString("");
}
}
}
private void CopyCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
// Verify relevant conditions and set CanExecuteRoutedEventArgs.CanExecute accordingly
e.CanExecute = true;
}
private void CopyCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
// Execute the command action
if (sender is EMS_UI_LCDscreen lcd)
{
if (TheDevice!=null)
Clipboard.SetDataObject(TheDevice.GetStructuredLocation(0).ToString());
else
Clipboard.SetDataObject(lcd.StructuredTextToShow.ToString());
}
}
private void PasteCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
// Verify relevant conditions and set CanExecuteRoutedEventArgs.CanExecute accordingly
IDataObject iData = Clipboard.GetDataObject();
// Is the Data Text?
if (iData.GetDataPresent(DataFormats.Text))
e.CanExecute = true;
else
e.CanExecute = false;
}
private void PasteCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
// Execute the command action
if (sender is EMS_UI_LCDscreen lcd)
{
// Retrieves data
IDataObject iData = Clipboard.GetDataObject();
// Is the Data Text?
if (iData.GetDataPresent(DataFormats.Text))
{
if (TheDevice != null)
{
TheDevice.SetLocation(0, (string)iData.GetData(DataFormats.Text));
lcd.StructuredTextToShow = TheDevice.GetStructuredLocation(0);
}
else
{
lcd.StructuredTextToShow.SetString((string)iData.GetData(DataFormats.Text));
}
}
}
}
Finally, the ContextMenu is assigned to the object in the constructor:
public EMS_UI_LCDscreen()
{
InitializeComponent();
// Find the ContextMenu created on this object - it is called cmLCD_CopyCutPaste
ContextMenu cm = FindResource("cmLCD_CopyCutPaste") as ContextMenu;
// If we found the contextMenu, assign it the ContextMenu placeholder for this instance.
if (cm != null)
{
ContextMenu = cm;
}
...
The menu is shown on the component in response to right-click, the cut/copy/paste methods respond to the key ops, but clicking on the menu items does not fire the corresponding methods.
I can't see why that should be so, it all looks correct to me, but perhaps there is something missing that is preventing it working. One suggestion was to use a "relay command" type of thingy, but what and how that may be, is unclear.
You should remove all code that sets IsEnabled to true. It's redundant as the value is true by default.
The buttons are disabled because you have (accidentally?) attached a command to the MenuItem.Command property but no corresponding command handler.
The framework will try to invoke a CanExecute handler. Since there is no one defined, a default handler is returned that sets CanExecuteRoutedEventArgs.CanExecute to false, which will disable the button (ICommandSource).
Not sure if your intention was to use a command here or you wrongfully guessed the Command property is like a name property (since you have also registered Click event handlers). See Commanding Overview to learn more.
Anyway, this is how you can register a command handler:
You have assigned predefined application commands (cut, copy and paste - the MenuItem.Command string values in your XAML implicitly references the static ApplicationCommands commands). These commands are routed commands (behavior is identical to routed events - in fact routed commands are routed events). Therefore, you must define the command bindings on a parent element of the command source (the element that invokes the command) as the command will bubble up the tree.
A UIElement.CommandBinding consists of the specified CommandBinding.Executed handler and the optional CommandBinding.CanExecute handler.
Use the CanExecute handler to control the disabled states of the command source e.g., a Button. If the command source should be always enabled, simply omit the CanExecute handler.
XAML
<Window>
<Window.CommandBindings>
<CommandBinding Command="Cut"
CanExecute="CutCommand_CanExecute"
Executed="CutCommand_Executed" />
</Window.CommandBindings>
</Window>
C#
partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var cutCommandBinding =
new CommandBinding(ApplicationCommands.Cut, CutCommand_Executed, CutCommand_CanExecute)
this.CommandBindings.Add(cutCommandBinding);
}
}
Then create the corresponding command handlers in the code-behind.
private void CutCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
// Verify relevant conditions and set CanExecuteRoutedEventArgs.CanExecute accordingly
e.CanExecute = true;
}
private void CutCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
// Execute the command action
}
Update
To force command handling on the UserControl, you can explicitly set the MenuItem.CommandTarget property to reference the UserControl.
You can also assign the UserControl.Contextmenu from XAML:
<UserControl>
<UserControl.Resources>
<Style TargetType="MenuItem">
<Setter Property="CommandTarget"
Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget}" />
</Style>
</UserControl.Resources>
<UserControl.Contextmenu>
<ContextMenu>
<MenuItem Name="CutOption" Header="{x:Static p:Resources.Popup_Cut}" Command="{Binding Cut}"/>
<MenuItem Name="CopyOption" Header="{x:Static p:Resources.Popup_Copy}" Command="{Binding Copy}"/>
<MenuItem Name="PasteOption" Header="{x:Static p:Resources.Popup_Paste}" Command="{Binding Paste}"/>
</ContextMenu>
</UserControl.Contextmenu>
<UserControl.CommandBindings>
<CommandBinding Command="Cut"
CanExecute="CutCommand_CanExecute"
Executed="CutCommand_Executed" />
<CommandBinding Command="Copy"
CanExecute="CopyCommand_CanExecute"
Executed="CopyCommand_Executed" />
<CommandBinding Command="Paste"
CanExecute="PasteCommand_CanExecute"
Executed="PasteCommand_Executed" />
</UserControl.CommandBindings>
</UserControl>
This was the solution that finally worked for me. The elixir was assigning the commands, not with the "Binding" term, but directly:
<UserControl x:Class="EMS_Config_Tool.UIComponents.WPF.EMS_UI_LCDscreen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:p="clr-namespace:EMS_Config_Tool.Properties"
mc:Ignorable="d"
d:DesignHeight="66" d:DesignWidth="340" Focusable="True" KeyDown="Grid_KeyDown" MouseRightButtonDown="EMS_UI_LCDscreen_MouseRightButtonDown" >
<UserControl.Resources>
<Style TargetType="MenuItem">
<Setter Property="CommandTarget"
Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget}" />
</Style>
</UserControl.Resources>
<UserControl.ContextMenu>
<ContextMenu>
<MenuItem Name="CutOption" Header="{x:Static p:Resources.Popup_Cut}" Command="Cut" />
<MenuItem Name="CopyOption" Header="{x:Static p:Resources.Popup_Copy}" Command="Copy" />
<MenuItem Name="PasteOption" Header="{x:Static p:Resources.Popup_Paste}" Command="Paste" />
</ContextMenu>
</UserControl.ContextMenu>
<UserControl.CommandBindings>
<CommandBinding Command="Cut"
CanExecute="CutCommand_CanExecute"
Executed="CutCommand_Executed" />
<CommandBinding Command="Copy"
CanExecute="CopyCommand_CanExecute"
Executed="CopyCommand_Executed" />
<CommandBinding Command="Paste"
CanExecute="PasteCommand_CanExecute"
Executed="PasteCommand_Executed" />
</UserControl.CommandBindings>
</UserControl>
The constructor and assignment of images looks like this:
public EMS_UI_LCDscreen()
{
InitializeComponent();
Image ObjImage1 = new Image();
Image ObjImage2 = new Image();
Image ObjImage3 = new Image();
ObjImage1.Source = new BitmapImage(new Uri(#"pack://application:,,,/Graphics\Misc Icons\Cut.png"));
CutOption.Icon = ObjImage1;
ObjImage2.Source = new BitmapImage(new Uri(#"pack://application:,,,/Graphics\Misc Icons\Copy.png"));
CopyOption.Icon = ObjImage2;
ObjImage3.Source = new BitmapImage(new Uri(#"pack://application:,,,/Graphics\Misc Icons\Paste.png"));
PasteOption.Icon = ObjImage3;
...
... and displaying the context menu on the component in response to the mouse right click:
private void EMS_UI_LCDscreen_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
if (ContextMenu is ContextMenu cm)
{
if (DataContext is DeviceEditorData ded)
{
cm.DataContext = ded.Device.GetStructuredLocation((uint)LocationIndex);
cm.IsEnabled = true;
cm.PlacementTarget = sender as EMS_UI_LCDscreen;
cm.IsOpen = true;
}
if (DataContext is EMSBasicDevice dev)
{
cm.DataContext = dev.GetStructuredLocation((uint)LocationIndex);
cm.IsEnabled = true;
cm.PlacementTarget = sender as EMS_UI_LCDscreen;
cm.IsOpen = true;
}
}
}
For brevity, I have not shown the ..._CanExecute / ...Executed methods, they are as shown previously in the question.
Thanks to all who have helped in resolving this issue.
View of the finished context Menu in situ
So, if you are using DataContext and Binding's, you can do the following
remove the direct control with event handlers, i.e. Click, and direct setting of Enabled.
use Binding to bind menu action to the handler inside the view model: Command={Binding CutCommand} (or any other handler).
use ICommand.CanExecute of the command handler (CutCommand in the sample above). to manage Enabled state of menu item.
So, let's put all together.
In the XAML
<MenuItem Name="CutOption" Header="{x:Static p:Resources.Popup_Cut}"
Command="{Binding CutCommand}"/>
In the ViewModel
class ViewModel: INotifyPropertyChanged
{
...
public ICommand CutCommand { get; }
public ViewModel()
{
//you can just omit second arg if you always can call Cut.
CutCommand = new RelayCommand(CutHandler, ()=>CanCut()));
}
...
}
Here RelayCommand is a https://learn.microsoft.com/en-us/windows/communitytoolkit/mvvm/relaycommand or any other implementation of simple command.
If you need to update the Enabled state on-the-fly, you can call CommandManager.InvalidateRequerySuggested(); to reevaluate CanExecute of all commands.

wpf textblock focus on mouse right click

hello I am pretty new to wpf c#, I have a treeview which is populated at run time and here is my xaml code
<StackPanel Orientation="Horizontal">
<Image Source="Properties\accessories-text-editor-6.ico" Margin="0,0,5,0" />
<TextBlock Text="{Binding Name}" Foreground="Green" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" MouseRightButtonDown="TextBlock_MouseRightButtonDown" >
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="HeadLine" ></MenuItem>
<MenuItem Header="Textblock" ></MenuItem>
<MenuItem Header="Author" ></MenuItem>
<MenuItem Header="PageNumber" ></MenuItem>
<MenuItem Header="RunningTitle" ></MenuItem>
<MenuItem Header="Illustration" ></MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</StackPanel>
what I want is when I right click the textblock that is inside the treeview. the textblock need to be focus. As of now what it does is show the context menu item.
so how do I get the index of the Right clicked textblock? so I can focus to that item.
Thank you
A TextBlock cannot be focused...but you can get a reference to it in the MouseRightButtonDown event handler by casting the sender argument:
private void TextBlock_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
TextBlock txt = sender as TextBlock;
//do whatever you want with the TextBlock...
}
If you are in the context of a TreeView you may want to select the parent TreeViewItem:
private void TextBlock_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
TextBlock txt = sender as TextBlock;
TreeViewItem tvi = FindParent<TreeViewItem>(txt);
if (tvi != null)
tvi.IsSelected = true;
}
private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
}

How to copy selected listview item by copy command in the context menu

I've a listview and I want to copy the selected item by selecting the copy command in the context menu. I'm able to create a context menu with the copy command as shown in the image below:
The problem is when I select a row item and right click it, the context menu wouldn't show and I cannot select the copy command to copy the selected item. The context menu will show when I right click at the empty space in the list view.
Here's the code:
.xaml
<ListView x: Name = "DebugLogLb" BorderBrush = "{x:Null}" SelectionMode = "Extended" MouseRightButtonDown = "DebugLogLb_MouseRightButtonDown">
<ListViewItem x: Name = "DebugLogItem">
<ListViewItem.ContextMenu>
<ContextMenu x: Name = "CommandMenu">
<MenuItem Header = "Clear log" Click = "CommandMenuItem_Click"/>
<MenuItem Header = "Copy" Command = "Copy" CommandTarget = "{Binding ElementName=DebugLogItem}"/>
</ContextMenu>
</ListViewItem.ContextMenu>
</ListViewItem>
</ListView >
.xaml.cs:
private void DebugLogLb_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
ContextMenu contextMenu = this.FindName("CommandMenu") as ContextMenu;
contextMenu.PlacementTarget = sender as ListViewItem;
contextMenu.IsOpen = true;
}
private void CommandMenuItem_Click(object sender, RoutedEventArgs e)
{
MenuItem menuItem = (MenuItem) e.OriginalSource;
switch (menuItem.Header.ToString())
{
case "Clear log":
DebugLogLb.Items.Clear();
break;
default:
break;
}
}
Something like this will let you use the ContextMenu with its MenuItems :
<ListView x:Name = "DebugLogLb" BorderBrush = "{x:Null}" SelectionMode = "Extended" ItemsSource="{Binding items}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}">
<TextBlock.ContextMenu >
<ContextMenu x:Name = "CommandMenu">
<MenuItem Header = "Clear log" />
<MenuItem Header = "Copy" Command = "Copy" CommandTarget = "{Binding ElementName=DebugLogItem}"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView >
So, define it inside the ItemTemplate in order to be able to use it when selecting each item.
The items collection is defined in code behind :
public ObservableCollection<string> items { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
items = new ObservableCollection<string>();
items.Add("first item");
items.Add("second item");
}
Nothing fancy, just for the sake of example.
One more thing, if you still want it available when clicking on the white space, add a ContextMenu on the ListView too:
<ListView.ContextMenu>
<ContextMenu x:Name = "CommandMenu">
<MenuItem Header = "Clear log" />
<MenuItem Header = "Copy" Command = "Copy" CommandTarget = "{Binding ElementName=DebugLogItem}"/>
</ContextMenu>
</ListView.ContextMenu>

ObservableCollection ListBox Item Remove Not Working

I have a ListBox with binding, when i add Items it works perfect but if i try to remove the items with contextMenu it doesnt work.
Here is what i try so far ListBox Xaml Code
<ListBox Name="lstPersons"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch" Margin="126,-228,2,-242">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu Name="PersonContext">
<toolkit:MenuItem Name="PersonDelete" Header="Delete" Click="DeletePerson_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="btnKellnerName"
Text="{Binding _PersonName}"
FontSize="35"
FontFamily="Portable User Interface"/>
<TextBlock Name="btnPosition"
Text="{Binding _PersonPosition}"
FontSize="22"/>
<TextBlock Name="lblUhrzeit"
Text="{Binding _CreationDate}"
FontSize="18"/>
<TextBlock Name="Space" Text=" "/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And the Binding Class Code
public class Person
{
public string _PersonName { get; set; }
public string _PersonPosition { get; set; }
public string _CreationDate { get; set; }
}
When i add items like this
ObservableCollection<Person> personList = new ObservableCollection<Person>();
personList.Add(new Person {
_PersonName = "Tom",
_PersonPosition = "Bla",
_CreationDate = "33"
});
this.lstPerson.ItemSource = personList;
it works pefect! Now i Want to remove a selected Item with the ContextMenu like this
private void DeletePerson_Click(object sender, RoutedEventArgs e)
{
int indexPerson = lstPerson.SelectedIndex;
personList.RemoveAt(indexPerson);
}
but it doesnt work. Does Anybody have an Idea what im making wrong? Thanks
Ok Guys i have now the Solution the Problem was the value of SelectedIndex now ive got the right Value. First ive put the ContextMenu inside ListBoxItemTemplate/StackPanel
Code Behind:
private void DeletePerson_Click(object sender, RoutedEventArgs e)
{
try {
var selectedListBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(((MenuItem) sender).DataContext) as ListBoxItem;
var selectedIndex = listBox.ItemContainerGenerator.IndexFromContainer(selectedListBoxItem);
_personList.RemoveAt(selectedIndex);
}
catch( Exception ex ) { MessageBox.Show(ex.Message); };
}
In addition to what Joan said, you can also do this in Xaml like this:
<ListBox ItemsSource={Binding personList}
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch" Margin="126,-228,2,-242">
<toolkit:ContextMenuService.ContextMenu>
</ListBox>
You should read how to use Bindings and the MVVM-Model. It's pretty convenient for stuff like this.
Here are some links:
http://channel9.msdn.com/Events/MIX/MIX10/EX14
http://channel9.msdn.com/Events/MIX/MIX11/OPN03
Don't get discouraged. It's a bit of learning at the beginning, but it's totally worth it. I also had some problems with displaying lists, before I started doing everything with MVVM using Laurent Bugnions' MvvmLight package.
try this:
private void DeletePerson_Click(object sender, RoutedEventArgs e)
{
System.Collections.IList pathRemove;
pathRemove = lstPerson.SelectedItems;
if(pathRemove.Count != 0)
{
for (int i = pathRemove.Count - 1; i >= 0; i--)
{
lstPerson.Remove((Person)pathRemove[i]);//multiple deletes
}
}
}
Try to add this when the form is initialized:
lstPersons.ItemsSource = personList ;
How to: Create and Bind to an ObservableCollection
It appears that the problem is due to selected item
The key is setting the PreviewMouseRightButtonDown event in the
correct place. As you'll notice, even without a ContextMenu right
clicking on a ListViewItem will select that item, and so we need to
set the event on each item, not on the ListView.
<ListView>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<EventSetter Event="PreviewMouseRightButtonDown"
Handler="OnListViewItemPreviewMouseRightButtonDown" />
</Style>
</ListView.ItemContainerStyle>
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="Menu Item">Item 1</MenuItem>
<MenuItem Header="Menu Item">Item 2</MenuItem>
</ContextMenu>
</ListView.ContextMenu>
<ListViewItem>Item</ListViewItem>
<ListViewItem>Item</ListViewItem>
<ListViewItem>Item</ListViewItem>
<ListViewItem>Item</ListViewItem>
<ListViewItem>Item</ListViewItem>
<ListViewItem>Item</ListViewItem>
</ListView>
.
private void OnListViewItemPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
Trace.WriteLine("Preview MouseRightButtonDown");
e.Handled = true;
}
wpf listview right-click problem
Why don't use binding for all.
Bind item source as ObservableCollection blabla
Bind Selecteditem as XXXX
Use command for your button and when you want remove an item do :
blabla.remove(SelectedItem);

Getting WPF Data Grid Context Menu Click Row

I have a WPF DataGrid
<DataGrid AutoGenerateColumns="False" Name="dataGrid1" IsReadOnly="True" >
<DataGrid.Columns>
<DataGridTextColumn Header="Site" Binding="{Binding Site}" Width="150" />
<DataGridTextColumn Header="Subject" Binding="{Binding Subject}" Width="310" />
</DataGrid.Columns>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete" Click="Context_Delete">
<MenuItem.Icon>
<Image Width="12" Height="12" Source="Images/Delete.png" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
I have the click event handler as:
private void Context_Delete(object sender, System.EventArgs e) { }
How do I get the row on which the Context Menu was before the click? The sender object is System.Windows.Controls.MenuItem, not the DataGridRow. How do I get the DataGridRow where the Context Menu was clicked. (I set the DataGrid.ItemSource in the code behind file.)
So based on your example code, I presume you bind your DataGrid to an ObservableCollection of objects of which you bind the properties Site and Subject to the DataGridColumns.
Essentially, all you need to do is figure out what the item bound to the clicked DataGridRow is and remove that from your ObservableCollection. Here is some example code to get you started:
private void Context_Delete(object sender, RoutedEventArgs e)
{
//Get the clicked MenuItem
var menuItem = (MenuItem)sender;
//Get the ContextMenu to which the menuItem belongs
var contextMenu = (ContextMenu)menuItem.Parent;
//Find the placementTarget
var item = (DataGrid)contextMenu.PlacementTarget;
//Get the underlying item, that you cast to your object that is bound
//to the DataGrid (and has subject and state as property)
var toDeleteFromBindedList = (YourObject)item.SelectedCells[0].Item;
//Remove the toDeleteFromBindedList object from your ObservableCollection
yourObservableCollection.Remove(toDeleteFromBindedList);
}
Typically, you do not deal with rows (if you do - think again about the reasons) - instead you work with view model. When you open context menu, you get your item selected, so it can be accessed via the DataGrid.SelectedItem property. However, if you really need DataGridRow - you have your DataGrid.SelectedIndex and there is a lot of answers here on SO on how to get the row. like Get row in datagrid
To expand morincer's point above with an example, I ended up with a simpler approach...
private void MenuItem_OnClickRemoveSource(object sender, RoutedEventArgs e)
{
if (SourceDataGrid.SelectedItem == null) return; //safety first
_importViewModel.SourceList.Remove((SourceFileInfo)SourceDataGrid.SelectedItem);
}
In my case, the
_importViewModel.SourceList
is the ObservableCollection the rows are bound to. So per best practices, I simple remove the selected item from the collection and the binding takes care of the UI.
dsfgsho's answer worked for me, but right clicking on a grid row does not automatically select it. This means that if your focus is elsewhere and you right-click and select a context menu item, you can get an out of range exception on item.SelectedCells[0], or if you have a row selected and right-click on a different row, you may get unexpected results.
I dealt with this by handling "PreviewMouseRightButtonDown" on the Datagrid. Here I am explicitly selecting a row when it is right-clicked. I forget where my UIHelpers class came from (probably elsewhere on this site - I was using it to resolve drag & drop items), but this should point you in the right direction if you are running into this problem. This is an extension of the accepted answer:
// handle right mouse click to select the correct item for context menu usage
private void myDataGrid_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
//find the clicked row
DataGridRow row = UIHelpers.TryFindFromPoint<DataGridRow>((UIElement) sender, e.GetPosition(myDataGrid));
if (row == null)
{
Debug.WriteLine("Row is null");
return;
}
else
{
Debug.WriteLine("Grid Row Index is " + row.GetIndex().ToString());
(sender as DataGrid).SelectedIndex = row.GetIndex();
}
}
Elemental Pete's UIHelper probably stemmed from:
http://www.hardcodet.net/2009/03/moving-data-grid-rows-using-drag-and-drop
This Article lists a Zip that contains UIHelper.cs.
It's not my Code so no copy/paste here.
The accepted answer from dsfgsho makes sense but when using CommandBinding for the standard ApplicationCommands rather than an explicit Click event it is a little different as the sender is not the MenuItem but the DataGrid itself.
XAML:
<DataGrid.CommandBindings>
<CommandBinding Command="Cut" CanExecute="DataGrid_CanCut" Executed="DataGrid_Cut" />
<CommandBinding Command="Copy" CanExecute="DataGrid_CanCopy" Executed="DataGrid_Copy" />
<CommandBinding Command="Paste" CanExecute="DataGrid_CanPaste" Executed="DataGrid_Paste" />
<CommandBinding Command="New" CanExecute="DataGrid_CanAddNew" Executed="DataGrid_AddNew" />
<CommandBinding Command="Delete" CanExecute="DataGrid_CanDelete" Executed="DataGrid_Delete" />
</DataGrid.CommandBindings>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Command="Cut" />
<MenuItem Command="Copy" />
<MenuItem Command="Paste" />
<MenuItem Command="New" />
<MenuItem Command="Delete" />
<Separator />
<MenuItem Header="Test" Command="{Binding CustomContextCommand}" />
</ContextMenu>
</DataGrid.ContextMenu>
Code Behind:
private void DataGrid_Delete(object sender, ExecutedRoutedEventArgs e)
{
// Test whether cleared, resolved, etc., and confirm deletion
var datagrid = (DataGrid)sender;
var trans = (DataClasses.BankTransaction)datagrid.SelectedCells[0].Item;
// Take action here; e.g., remove it from the underlying collection, remove it
// from the DB, etc.
e.Handled = true;
}
private void DataGrid_CanDelete(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
e.Handled = true;
}

Categories

Resources