How to hook up OnClick event to WPF button inside ListBox <DataTemplate> from codebehind
I need to find a way to bind an event (OnClick) to a button that is part of a ListBox, inside the ListItem and DataTemplate. This is done from the C # scripting space inside another application that doesn't accept event binding from XAML code, but allows me to do the binding at runtime. For other controls that are not inside a data template like the lstSaveSetups ListBox, I use the LogicalTreeHelper, find the item I want and just bind it. It doesn't work here and I've also tried FindName unsuccessfully as well as many other approaches.
This is the XAML:
<ListBox Name="lstSavedSetups" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="50" />
<ColumnDefinition Width="25" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding 1stColumn}" />
<TextBlock Grid.Column="1" Text="{Binding 2ndColumn}" />
<Button Grid.Column="2" Name="btnDelete" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Simplified C # code:
System.IO.FileStream fs = new System.IO.FileStream(System.IO.Path.Combine(myBaseDir, @"listBox.xaml"), System.IO.FileMode.Open);
System.Windows.Controls.Page page = (System.Windows.Controls.Page)System.Windows.Markup.XamlReader.Load(fs);
lstSavedSetups = LogicalTreeHelper.FindLogicalNode(page, "lstSavedSetups") as System.Windows.Controls.ListBox;
System.Windows.Controls.Grid.SetRow(lstSavedSetups, 16);
System.Windows.Controls.Grid.SetColumn(lstSavedSetups, 1);
myGrid.Children.Add(lstSavedSetups);
//the following works
lstSavedSetups.SelectionChanged += lstSavedSetups_SelectionChanged;
//one of many examples of what does not work:
System.Windows.Controls.Button btnDelete = lstSavedSetups.ItemTemplate.FindName("btnDelete", lstSavedSetups) as System.Windows.Controls.Button;
btnDelete.Click += btnDelete_OnClick;
I haven't included everything I've tried, but I'm starting to think that I've tried every solution I could find, but I haven't been able to get this to work.
What am I doing wrong? Any help would be really appreciated! Thank!
Libor
source to share
No one has answered this question yet
See similar questions:
or similar: