HOW CAn I Differciate the button click Event
i have a problem. i m making Some wpf button Dynamic through C#.i m using it A loop for this now i m trying to find all button Click Event. i find it But It Work Same on All The button Click how Can i Differciate all the button .
thanks in Advance shashank
`for (int i = 0; i < 2; i++)
{
Button b1 = new Button();
//this.RegisterName("myAnimatedBrush", b1);
b1.Name = "button" + i;
b1.Height = 200;
b1.Width = 200;
b1.Margi开发者_如何学运维n = new Thickness(0, -100, 0, 0);
b1.HorizontalAlignment = HorizontalAlignment.Left;
b1.Content = "English";
b1.Background = System.Windows.Media.Brushes.Pink;
b1.Click+=new RoutedEventHandler(b1_Click);
canvasbtn.Children.Add(b1);
Canvas.SetLeft(b1,b1.Width * i);
}`
My two cents:
If you want the buttons you create in a loop to all behave differently, think about what is different about the buttons themselves and check for that. For example:
- If each button is generated from a different data item, set its DataContext and use that to find the original data item.
- If each buttons is numbered, set the DataContext to the button number.
- If each button has a different meaning, set the Click to different event handlers. You can create an array of these. Or have a different object attached to each button as a CommandParameter.
Your code will be most meaningful if you distinguish your behavior based on something that is salient to the end-user.
Example:
for(int i=0; 0<10; i++)
{
var btn = new Button
{
DataContext = i,
Height = 200, Width = 200,
Margin=new Thickness(0, 100, 0 0),
});
btn.Click += (sender, e) =>
{
MessageBox.Show("You clicked button " + ((Button)sender).DataContext);
};
dockPanel.Children.Add(btn); // Or you could use Canvas & Canvas.SetLeft
}
I would recommend you strongly consider using DockPanel instead of Canvas for this. Unless you need arbitrary positioning by the end-user (drag and drop), Canvas is almost never the right panel to use. If you use a DockPanel you won't have to set the left coordinate - it will automatically do this for you.
May be somthing like this would work.
protected void HandleBtnClick(object sender, EventArgs args)
{
Button btn = sender as Button;
if(btn==null){
return; //This is not expected.
}
if(btn.Name=="button1")
{
DoFirstTask();
}
else if (btn.Name == "button2")
{
DoSecondTask();
}
...
}
void b1_Click(object sender, RoutedEventArgs e)
{
Button srcButton = e.Source as Button;
}
Source & More
精彩评论