I have a WPF user contol, in which I have a StackPanel. To this panel I'm adding programatically a label this way (Container is the name of StackPanel):
public void Insert(string Value)
{
Label l = new Label();
l.Content = Value;
Container.Children.Add(l);
}
Now I want to provide some public 开发者_如何学Goevent SelectedIndexChange, when user clicks on label. Now I have a problem how determine which label was clicked. Can someone help?
If in Insert
you add the line:
l.Click += ClickHandler;
then the first argument of ClickHandler will be the control that raised the Click event.
e.g. If your handler is:
private void ClickHandler(object sender, RoutedEventArgs e){...};
then sender
will be the label that was clicked.
You could alternatively look at e.OriginalSource
.
I Guess You Can Use This Code
l.MouseClick+= MouseClickHandler;
And Switch Between Lables
Example:
private void label1_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton== MouseButtonState.Pressed)
{
Label l = (Label)e.Source;
switch (l.Name)
{
case "lable1":
int a = 10;
break;
}
}
}
精彩评论