With a little work, I found the following solution:
The template in Generic.xaml looks like this:
<Style TargetType="{x:Type local:FloatEditButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:FloatEditButton}">
<Grid Margin="0">
<TextBlock x:Name="PART_TextBlock" Grid.Row="1"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Margin="0"
FontSize="{TemplateBinding FontSize}"
></TextBlock>
<Canvas x:Name="SliderCanvas" Grid.Row="1" IsHitTestVisible="False" Margin="0,3,0,2">
<Rectangle x:Name="PART_SliderDefaultRectangle" Width="1" Height="3" Canvas.Bottom="0" Fill="Black"/>
<Rectangle x:Name="PART_SliderMarkerRectangle" Width="1" Canvas.Top="0" Canvas.Left="20" Fill="#30ffffff" Height="{Binding ElementName=SliderCanvas, Path=ActualHeight}" />
<Rectangle x:Name="PART_SliderFillRectangle" Width="10" Fill="#10ffffff" Height="{Binding ElementName=SliderCanvas, Path=ActualHeight}" />
</Canvas>
<TextBox x:Name="PART_TextBox"
Visibility="Collapsed"
FontSize="{TemplateBinding FontSize}"
VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The initialization function looks something like this: the important part is to overwrite OnApplyTemplate and use GetTemplateChild ().
public override void OnApplyTemplate() {
base.OnApplyTemplate();
_textBox = GetTemplateChild("PART_TextBox") as TextBox;
MouseLeftButtonDown+= MouseLeftButtonDownHandler;
MouseLeftButtonUp+= MouseLeftButtonUpHandler;
MouseMove+= MouseMoveHandler;
MouseWheel+= MouseWheelHandler;
LayoutUpdated+=LayoutUpdatedHandler;
if (_textBox !=null) {
_textBox.TextChanged += TextChangedHandler;
_textBox.KeyUp += KeyUpHandler;
_textBox.LostFocus += LostFocusHandler;
}
_sliderFillRectangle = GetTemplateChild("PART_SliderFillRectangle") as Rectangle;
_sliderDefaultRectangle = GetTemplateChild("PART_SliderDefaultRectangle") as Rectangle;
_sliderMarkerRectangle = GetTemplateChild("PART_SliderMarkerRectangle") as Rectangle;
_textBlock = GetTemplateChild("PART_TextBlock") as TextBlock;
}
Internal member variables are later used as ...
private void LostFocusHandler(object sender, RoutedEventArgs e) {
if (!UpdateValueFromTextEdit())
_textBox.Text = Value.ToString();
_textBox.Visibility = Visibility.Collapsed;
e.Handled= true;
}
Refactoring from UserControl to CustomControl speeds up installation by 50%;
source
share