Reputation: 5394
I have not been able to find any examples of this. Having a UserControl defined below with the customcontrol, SimpleTextBlock (that inherits from TextBlock), I would like to use the OnApplyTemplate() event in the usercontrol code-behind to grab some of the properties known only to the SimpleTextBlock only after being rendered at run-time.
This code does not work. How is this done?
XAML
<UserControl x:Class="Nova5.UI.Views.Ink.InkEditorView"
..........
<Grid Background="#FFE24848" >
..........
<Canvas Grid.Row="1" Grid.RowSpan="3">
<ScrollViewer VerticalScrollBarVisibility="Auto"
Width="{Binding Parent.ActualWidth, Mode=OneWay, RelativeSource={RelativeSource Self}}"
Height="{Binding Parent.ActualHeight, Mode=OneWay, RelativeSource={RelativeSource Self}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<fsc:SimpleTextBlock x:Name="PART_SimpleTextBlock"
Background="#FFE24848"
RichText="{Binding RichText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
FontSize="{Binding FontSize, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
FontStyle="{Binding FontStyle, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
FontWeight="{Binding FontWeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
FontFamily="{Binding FontFamily, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
/>
</Grid>
</ScrollViewer>
</Canvas>
</Grid>
C# code-behind:
[TemplatePart(Name = "PART_SimpleTextBlock", Type = typeof(TextBlock))]
public partial class InkEditorView : UserControl
{
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
*** t IS NULL ????
SimpleTextBlock t = (SimpleTextBlock)base.GetTemplateChild("PART_SimpleTextBlock");
}
What am I missing? (Be kind :) ) Thanks for any help.
Upvotes: 3
Views: 4449
Reputation: 39006
OnApplyTemplate
only works inside a custom control, not a usercontrol. :)
Your C# code is the implementation of a custom control however your xaml code is to create a usercontrol.
Basically, a usercontrol is what you use to group a few controls and panels together while a custom control is just like a Button
, a CheckBox
or a ListView
. Normally you want to create a custom control when you want to extend an existing control. In your case, looks like you want to extend the UserControl
.
This link has a comparison between them too and also a good example of how to create one.
Upvotes: 4