Event handler arguments
I am using the following code to add buttons to a list:
for (int i=0; i < mov.Theat.Count(); i++)
{
StackPanel st=new StackPanel();
st.Orientation=System.Windows.Controls.Orientation.Horizontal;
st.HorizontalAlignment = HorizontalAlignment.Center;
TextBlock tx = new TextBlock();
tx.Text=mov.Theat[i];
st.Children.Add(tx);
TextBlock tx2=new TextBlock();
tx2.Text=mov.Time[i];
st.Children.Add(tx2);
Button test = new Button();
test.Width=450;
test.Content = st;
test.Click += new RoutedEventHandler(Button_Click);
theatlist.Items.Add(test);
}
As for the event handler, it is shown 开发者_如何学Gobelow:
void Button_Click(object sender, RoutedEventArgs e)
{
Theat_Data TD=(App.Current as App).Theat.First(theat => theat.Name=="");
PhoneApplicationService.Current.State["Theat"] = TD;
this.GoToPage(ApplicationPages.Theat);
}
I want to pass some variable about the selected button in the even handler so how can this be done? And if this is not possible, then what options do I have to identify the button and pass some data about it to the event handler?
I assume your business object is called Thead_Data and you would like to have access to this object from within your Click-method:
During creation, attach your data object to the DataContext or the Tag property:
Button test = new Button(){DataContext=Theat[i]};
Within your event handler, cast the DataContext or the Tag-property to your business-object:
void Button_Click(object sender, RoutedEventArgs e){
Button btn=(Button)sender;
Theat_Data td=(Theat_Data)button.DataContext;
...
}
You can access the sender like this:
void Button_Click(object sender, RoutedEventArgs e)
{
var clickedButton = sender as Button;
}
I'm not sure I completely understand what you are asking, but the "sender" param of the event handler is the button. You should just be able to cast it:
Button b = (Button)sender;
You could write your own event handler and add your custom data in the event args.
精彩评论