0
votes

XAML

 <Grid>
    <TreeView Name="tr">
        <TreeView.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Malfunction" Name="mi" Click="mi_Click">                                                            </MenuItem>
            </ContextMenu>

        </TreeView.ContextMenu>
    </TreeView>

Code Behind

namespace ContextMenuExamples {

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        List<Device> lst = new List<Device>();
        lst.Add(new Device() { DeviceId = 1, DeviceName = "Device1" });
        lst.Add(new Device() { DeviceId = 2, DeviceName = "Device2" });
        lst.Add(new Device() { DeviceId = 3, DeviceName = "Device3" });
        lst.Add(new Device() { DeviceId = 4, DeviceName = "Device4" });
        lst.Add(new Device() { DeviceId = 5, DeviceName = "Device4" });
        tr.ItemsSource = lst;
        tr.DisplayMemberPath = "DeviceName";
        List<Malfunction> mf = new List<Malfunction>();
        mf.Add(new Malfunction() { MalfunctionName = "Malfunction1", Id = 1 });
        mf.Add(new Malfunction() { MalfunctionName = "Malfunction2", Id = 2 });
        mf.Add(new Malfunction() { MalfunctionName = "Malfunction3", Id = 3 });
        mf.Add(new Malfunction() { MalfunctionName = "Malfunction4", Id = 4 });
        mf.Add(new Malfunction() { MalfunctionName = "Malfunction5", Id = 5 });
        mf.Add(new Malfunction() { MalfunctionName = "Malfunction6", Id = 6 });
        mi.ItemsSource = mf;
        mi.DisplayMemberPath = "MalfunctionName";
    }

    private void mi_Click(object sender, RoutedEventArgs e)
    {
        /*here  value of clicked **Malfunction** object required. if I click  
        Malfunction6. Then I should get MalfunctionName ="Malfunction6"* and     Id =6*/
    }
}
public class Device
{
    public string DeviceName { get; set; }
    public int DeviceId { get; set; }
}
public class Malfunction
{
    public string MalfunctionName { get; set; }
    public int Id { get; set; }
}

}


Image

ContextMenu, Clicked MenuItem

Here my query is how to get reference of clicked menu item object in menu click event. If I click Malfunction6 menu item. Then it should get MalfunctionName ="Malfunction6" and Id =6

1
Cast the sender to menuitem ?Felix D.

1 Answers

2
votes

The MenuItem clicked is passed in the RoutedEventArgs e OriginalSource variable. Then in the variable the class is stored in the Header variable.

    private void mi_Click(object sender, RoutedEventArgs e)
    {
        /*here  value of clicked **Malfunction** object required. if I click  
        Malfunction6. Then I should get MalfunctionName ="Malfunction6"* and     Id =6*/

        System.Windows.Controls.MenuItem mi = e.OriginalSource as System.Windows.Controls.MenuItem;
        Malfunction m = mi.Header as Malfunction;

        System.Console.WriteLine(m.MalfunctionName);
        System.Console.WriteLine(m.Id);
    }