Reputation: 813
Here is my XAML. The UserControl is named "Event"
<UserControl.Resources>
<Style x:Key="eventStyle" TargetType="Thumb">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Rectangle Name="rect" Fill="CadetBlue" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Canvas>
<Thumb Canvas.Left="0" Canvas.Top="0" Name="MoveThumb" Style="{StaticResource eventStyle}" Cursor="SizeAll" DragDelta="MoveThumb_DragDelta" DragStarted="MoveThumb_DragStarted" DragCompleted="MoveThumb_DragCompleted" />
</Canvas>
And here is the code behind
var ev = new Event();
var rect = ev.Template.FindName("rect", ev) as Rectangle;
But it doesn't work : the "rect" variable is null. What am I doing wrong ?
Thanks
Upvotes: 0
Views: 993
Reputation: 25201
The template you're defining is applied to the Thumb
control, and not the Event
control - that's why there's no rect
control in Event
's template.
Since you're creating the Event
control from another class, what you can do is expose the MoveThumb
control as a property in Event
's code-behind, like this:
public Thumb TheThumb
{
get { return MoveThumb; }
}
Then you can change your code to this:
var ev = new Event();
var rect = ev.TheThumb.Template.FindName("rect", ev.TheThumb) as Rectangle;
Better yet, you can expose the rect
control as a property:
public Rectangle Rect
{
get { return MoveThumb.Template.FindName("rect", MoveThumb) as Rectangle; }
}
and use it like this
var ev = new Event();
var rect = ev.Rect;
Upvotes: 2
Reputation: 11591
It returned null because the function FindName("controlName",TemplatedParent) expects a control on which the template is applied as the second parameter. From the code you've provided, I couldn't see when the template was applied to the control (ev used to the default template). Hence, the rect variable was null.
Try this
var rectangle = MoveThumb.Template.FindName("rect", MoveThumb) as Rectangle;
More information is available here and here
Upvotes: 1