Why does TemplateBinding
seems to fail in this specific case?
Take a basic extended button:
public class IconButton : Button
{
public ImageSource Icon
{
get { return (ImageSource)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public static readonly DependencyProperty ImageProperty =
DependencyProperty.Register("Icon", typeof(ImageSource), typeof(IconButton), new PropertyMetadata(null));
public IconButton()
{
DefaultStyleKey = typeof(IconButton);
}
}
The control template shows the icon using an OpacityMask
:
<Style TargetType="controls:IconButton">
<Setter Property="Width" Value="30" />
<Setter Property="Height" Value="30" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="controls:IconButton">
<Grid>
<Rectangle Fill="{StaticResource PhoneForegroundBrush}"
Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
<Rectangle.OpacityMask>
<ImageBrush ImageSource="{TemplateBinding Icon}" />
</Rectangle.OpacityMask>
</Rectangle>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This fails silently -- the control appears as a solid rectangle. If I use a regular image, instead of the ImageBrush
, then the binding is successful:
<ControlTemplate TargetType="controls:IconButton">
<Grid>
<Image Source="{TemplateBinding Icon}" />
</Grid>
</ControlTemplate>
It also works correctly if I hard-code the image source path:
<ControlTemplate TargetType="controls:IconButton">
<Grid>
<Rectangle Fill="{StaticResource PhoneForegroundBrush}"
Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
<Rectangle.OpacityMask>
<ImageBrush ImageSource="/Images/appbar.next.rest.png" />
</Rectangle.OpacityMask>
</Rectangle>
</Grid>
</ControlTemplate>
So, why does TemplateBinding
fail inside an ImageBrush
?
Update
By deduction (and thanks to the answer from Chris), possible factors are:
ImageBrush
inherits fromDependencyObject
rather than fromFrameworkElement
TemplateBinding
does not support implicit type conversion in the way that a normal binding does (ie, string-to-ImageSource)
I still don't see how the dots connect, though ...