Unable to find resource in an element.
I'm creating a custom control and its style. In the code behind I have this:
And in the ControlTemplate:
On Loaded I'm able to find the root grid, but it seems the grid doesn't have any of the resources. I'm pretty sure it's using that style because it is finding the root grid. I'm defining my style in my main resources file.
Code: Select all
Loaded += (s, e) =>
{
Grid root = (Grid)FindName("Root");
_tLeft = (ImageBrush)root.FindResource("TLeft");
...
};
Code: Select all
ControlTemplate TargetType="{x:Type local:NineSliceControl}">
<Grid x:Name="Root">
<Grid.Resources>
<Style TargetType="Rectangle">
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="RenderOptions.BitmapScalingMode" Value="NearestNeighbor" />
</Style>
<ImageBrush
x:Key="TLeft"
ImageSource="{TemplateBinding ImageSource}"
ViewboxUnits="Absolute" />
...
</Grid.Resources>
</Grid>
</ControlTemplate>
-
sfernandez
Site Admin
- Posts: 2983
- Joined:
Re: Unable to find resource in an element.
Hi,
Elements of the template visual tree cannot be get using FindName on the Control, because template elements have its own NameScope.
Template elements can be accessed using Template.FindName(name, templatedParent) instead:
I'm assuming here that this is the code behind of the custom control and that Template property is not null.
A better approach could be to define those resources in the ControlTemplate.Resources property, so you don't need to access the root of the template visual tree:
Elements of the template visual tree cannot be get using FindName on the Control, because template elements have its own NameScope.
Template elements can be accessed using Template.FindName(name, templatedParent) instead:
Code: Select all
Loaded += (s, e) =>
{
Grid root = (Grid)Template.FindName("Root", this);
_tLeft = (ImageBrush)root.FindResource("TLeft");
...
};
A better approach could be to define those resources in the ControlTemplate.Resources property, so you don't need to access the root of the template visual tree:
Code: Select all
<ControlTemplate TargetType="{x:Type local:NineSliceControl}">
<ControlTemplate.Resources>
<ImageBrush
x:Key="TLeft"
ImageSource="{TemplateBinding ImageSource}"
ViewboxUnits="Absolute" />
...
</ControlTemplate.Resources>
...
</ControlTemplate>
Code: Select all
Loaded += (s, e) =>
{
_tLeft = (ImageBrush)Template.FindResource("TLeft");
...
};
Who is online
Users browsing this forum: No registered users and 53 guests