I have defined the following DataTemplate for ListBox items in an external resource dictionary:
Using the OnApplyTemplate approach will work if you if you're working with the ControlTemplate for a Control. For example, if you've subclassed TextBox you could do this like
public class MyTextBox : TextBox
{
public override void OnApplyTemplate()
{
MySlider MySlider = GetTemplateChild("MySlider") as MySlider;
if (MySlider != null)
{
MySlider.ValueChanged += new RoutedPropertyChangedEventHandler(MySlider_ValueChanged);
}
base.OnApplyTemplate();
}
void MySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e)
{
//...
}
}
I don't think this approach will work in your situation however. You could use the Loaded event for ListBoxItem and find the Slider in the visual tree in the event handler
Code behind
private void ListBoxItem_Loaded(object sender, RoutedEventArgs e)
{
ListBoxItem listBoxItem = sender as ListBoxItem;
Slider MySlider = GetVisualChild(listBoxItem);
MySlider.ValueChanged += new RoutedPropertyChangedEventHandler(MySlider_ValueChanged);
}
void MySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e)
{
}
GetVisualChild
private static T GetVisualChild(DependencyObject parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild(v);
}
if (child != null)
{
break;
}
}
return child;
}