Title: Right-Click deleting in DataGrid from Dictionary<> in WPF
Tags: c#;wpf;dictionary;datagrid;mouseevent
Question: I have a DataGrid which receives it's values from a dictionary as such:
public class Files
{
public string File { get; set; }
public string Duration { get; set; }
public string Status { get; set; }
}
Dictionary<Files, string&gt; files = new Dictionary<Files, string&gt;();
DataGrid.ItemsSource = files.Keys;
Values are added programatically like this:
private void AddFilesList(string addsrc, string addduration, string addstatus, string path)
{
files.Add(new Files
{
File = addsrc,
Duration = addduration,
Status = addstatus,
}, path
);
DataGrid.Items.Refresh();
}
Now I am trying to add right-click/delete to the DataGrid which would delete the selected value from Dictionary.
I use MVVM pattern to delete the value as such, here is the XAML:
<Grid&gt;
<Grid DataContext="{Binding Source={StaticResource EmpVM}}"&gt;
<DataGrid AutoGenerateColumns="False" Height="287"
HorizontalAlignment="Left" Margin="23,12,0,0"
Name="DataGrid" VerticalAlignment="Top" Width="657"
SelectedIndex="{Binding Path=RecordIndex,Mode=TwoWay}"&gt;
<DataGrid.ContextMenu&gt;
<ContextMenu&gt;
<MenuItem Command="{Binding DeleteCommand}"
CommandParameter="{Binding RecordIndex}"  Header="Delete"/&gt;
</ContextMenu&gt;
</DataGrid.ContextMenu&gt;
</DataGrid&gt;
</Grid&gt;
Now the problem is that "Selectedindex" reflects the index of the selected value, and Dictionary<> does not have an index. This I am not able to remove the selecteditem after Index. I can't use OrderedDictionary either since I have to load a class into the dictionary.
Any suggestions anyone on how to bind the XAML to remove the selected item from Dictionary?
Comment: It's still index as an int.

Comment: Dev: Because it's loaded from a Class, so using selected value doesn't show the current value within the class, but just the general class.

Comment: Why not to use SelectedItem or SelectedValue and files.Remove()?

Comment: Have you tried: `files.Remove(files.Keys[SelectedIndex])`



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:12/02/12', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c#><wpf><dictionary><datagrid><mouseevent>', 'Title': 'Right-Click deleting in DataGrid from Dictionary<> in WPF', 'ViewCount': 630, 'id': 13667906, 'user_AboutMe': '<p>C#/Java</p>\n', 'user_AccountId': 1946172.0, 'user_DisplayName': 'Omid', 'user_Reputation': 803.0, 'user_Views': 96.0, 'user_id': 1751280.0}}