Using the OnApplyTemplate approach will work if you are working with a ControlTemplate for a control. For example, if you subclassed a TextBox , you could do this, for example
public class MyTextBox : TextBox { public override void OnApplyTemplate() { MySlider MySlider = GetTemplateChild("MySlider") as MySlider; if (MySlider != null) { MySlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(MySlider_ValueChanged); } base.OnApplyTemplate(); } void MySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) {
I do not think this approach will work in your situation. You can use the Loaded event for the ListBoxItem and find the Slider in the visual tree in the event handler
<ListBox ...> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <EventSetter Event="Loaded" Handler="ListBoxItem_Loaded"/> </Style> </ListBox.ItemContainerStyle> </ListBox>
Code for
private void ListBoxItem_Loaded(object sender, RoutedEventArgs e) { ListBoxItem listBoxItem = sender as ListBoxItem; Slider MySlider = GetVisualChild<Slider>(listBoxItem); MySlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(MySlider_ValueChanged); } void MySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { }
GetVisualChild
private static T GetVisualChild<T>(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<T>(v); } if (child != null) { break; } } return child; }
source share