Reputation: 55
(I'm crap at english, I hope it's okay)
I have something similar to a combo box, but instead it's a "menuItem combo-box". I tried to create a dynamic menu item that displays "History" objects dynamicaly.
And I have an issue with my code, I can't get the name of which item I click on..
Here is my wpf where you can see Click="myList_Click"; it's the trigger:
<Menu HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="525" IsMainMenu="True">
<MenuItem Header="Menu" x:Name="myList" Click="myList_Click">
<MenuItem.ItemContainerStyle>
<Style>
<Setter Property="MenuItem.Header" Value="{Binding name}"/>
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
</Menu>
Here is a part of MainWindow.cs :
public MainWindow()
{
var list = new List<History>
{
new History() { name = "Guy1"},
new History() { name = "Guy2"},
new History() { name = "Guy3"},
new History() { name = "Guy4"},
};
InitializeComponent();
this.myList.ItemsSource = list;
}
private void myList_Click(object sender, RoutedEventArgs e)
{
DependencyObject obj = (DependencyObject)e.OriginalSource;
while (obj != null && obj != myList)
{
if (obj.GetType() == typeof(MenuItem))
{
MessageBox.Show(myList.SelectedItem.ToString());
break;
}
obj = VisualTreeHelper.GetParent(obj);
}
}
Lastly, my simple class "History"
public class History
{
// "prop" puis "tab"
public String name { get; set; }
public String path { get; set; }
public int time { get; set; }
public override string ToString()
{
return name;
}
}
I thought about SelectedItem but it doesn't work, SelectedItem doesn't exist for my MenuItem class. I tried some methods for my MenuItem but none gave me anything useful.
I want to click on a menuitem, and then display its name. (Example: When I click on guy1, a popup should appear and show "Guy1").
I need this String to manipuate my software later.
Thank you very much for your help.
Upvotes: 1
Views: 448
Reputation: 2062
Try this :
private void myList_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show((e.OriginalSource as MenuItem).Header.ToString());
}
Upvotes: 1