I want to implement a WPF CustomControl, that…
- Normally looks like a button and displays a float value as string
- When dragging the button the float value is being manipulated like a virtual slider
- When clicking the button, it is replaced by a TextBox, prefilled with the current Value as String. This text can be edited. Clicking outside of the TextBox or pressing return will change the control back to Button and use the edited text as the new Value.
We need this control in a highly streamlined interface. Although the description sounds a little weird, it works amazingly well for us. But for performance reasons we now have to refactor the current implementation as a UserControl into a CustomControl.
I got the slider-part of the control running and managed to show a TextBox attached to a Content DependencyProperty. Sadly, however, I fail to access this TextBox from the ControlTemplate, which looks roughly like this:
<Style TargetType="{x:Type local:FloatEditButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:FloatEditButton}">
<Grid Margin="0">
<Viewbox VerticalAlignment="Center" HorizontalAlignment="{Binding RelativeSource={RelativeSource TemplatedParent},Path=HorizontalContentAlignment}" Margin="0">
<ContentPresenter Name="content" Margin="2" VerticalAlignment="Center" />
</Viewbox>
<TextBox x:Name="XTextBox" Visibility="Collapsed" Text="{Binding Content}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="EditingAsTextBox" Value="True">
<Setter TargetName="XTextBox" Property="Visibility" Value="Visible"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Any idea, how this could be implemented as a CustomControl?
After fumbling around a bit, I found the following solution:
The template in Generic.xaml looks like this…
The initializer function roughly looks like this: The important part is to overwrite OnApplyTemplate and use GetTemplateChild().
The internal member variables are later used like…
The refactoring from UserControl to CustomControl speeds up the instanziation by 50%;