I have defined the following DataTemplate
for ListBox
items in an external resource dictionary:
<DataTemplate x:Key="MyListBoxItemTemplate" DataType="{x:Type entities:Track}">
<StackPanel>
<TextBlock Text="Here's the slider:" />
<Slider Name="MySlider" Height="23" Minimum="0" />
</StackPanel>
</DataTemplate>
I need to provide an event handler method for Slider's ValueChanged
event. I don't know where am I supposed to write that code as it is impractical to specify event handler for a control within a template.
I've been googling for the solution and found that I should add the event handler in the override of the OnApplyTemplate()
method. My guess is that it should look something like this or similar:
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Is the following initialization even going to work!?!?
Slider MySlider = this.FindName("MySlider") as Slider;
SeekSlider.ValueChanged +=
new RoutedPropertyChangedEventHandler<double>(SeekSlider_ValueChanged);
}
But where should I write this method? Does OnApplyTemplate overriding only applies to ControlTemplates or is my scenario included as well? Should I provide ControlTemplate instead of DataTemplate? Is the body of the method I have provided correct?
Please help. Thanks.
Using the
OnApplyTemplate
approach will work if you if you're working with theControlTemplate
for a Control. For example, if you've subclassedTextBox
you could do this likeI don't think this approach will work in your situation however. You could use the Loaded event for
ListBoxItem
and find theSlider
in the visual tree in the event handlerCode behind
GetVisualChild