Why my dynamic click event does not work ? ( code attached )
I have some itemsControl that i dynamicly adding to it StackPanel as an item. Each of the StackPanel contain 2 button - btn1, btn2. I dynamicly connect each button to some button event ( all the button event are same ).
When i test it - i see that the event is not call on the button click - and i dont see any reason to this.
the Code:
private StackPanel CreatePanel()
{
StackPanel stackPanel = new StackPanel();
stackPanel.Orientation = Orientation.Horizontal;
for (int i =开发者_如何学JAVA 0; i < 2; i++)
{
Button btn = new Button();
btn.Height = btn.Width = 100;
btn.Content = i % 2 == 0 ? "Btn1" : "Btn2";
// Event connection
btn.Click += new RoutedEventHandler( button1_Click );
stackPanel.Children.Add(btn);
}
return stackPanel;
}
From MSDN: For certain combinations of input events and WPF control classes, the element that raises the event is not the first element that has the opportunity to handle it.
This is the nature of the RoutedEventHandler:)
try below code , works for me Please note grd is a Grid on my XAML
Edited added code for ItemsControl
XAML
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<ScrollViewer >
<Grid>
<ItemsControl Name="grd">
</ItemsControl>
</Grid>
</ScrollViewer>
Code
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
grd.Items.Add(CreatePanel()); // Now grd is a itemsControl
}
private StackPanel CreatePanel()
{
StackPanel stackPanel = new StackPanel();
stackPanel.Orientation = Orientation.Horizontal;
for (int i = 0; i < 2; i++)
{
Button btn = new Button();
btn.Height = btn.Width = 100;
btn.Content = i % 2 == 0 ? "Btn1" : "Btn2";
// Event connection
btn.Click += new RoutedEventHandler(doCall);
stackPanel.Children.Add(btn);
}
return stackPanel;
}
private void doCall(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hi");
}
}
精彩评论