[英]HOW CAn I Differciate the button click Event
i have a problem. 我有个问题。 im making Some wpf button Dynamic through C#.im using it A loop for this now im trying to find all button Click Event.
即时通讯使一些wpf按钮通过C#.im动态地使用它。为此,我尝试查找所有按钮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 在此先感谢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.Margin = 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:
例如:
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. 我强烈建议您为此考虑使用DockPanel而不是Canvas。 Unless you need arbitrary positioning by the end-user (drag and drop), Canvas is almost never the right panel to use.
除非最终用户需要任意放置(拖放),否则Canvas几乎永远不是使用的正确面板。 If you use a DockPanel you won't have to set the left coordinate - it will automatically do this for you.
如果您使用DockPanel,则无需设置左坐标-它会自动为您完成此操作。
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();
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.