【发布时间】:2014-03-02 22:11:43
【问题描述】:
为什么TemplateBinding 在这种特定情况下似乎失败了?
拿一个基本的扩展按钮:
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);
}
}
控件模板使用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>
这会静默失败——控件显示为实心矩形。如果我使用常规图像,而不是ImageBrush,则绑定成功:
<ControlTemplate TargetType="controls:IconButton">
<Grid>
<Image Source="{TemplateBinding Icon}" />
</Grid>
</ControlTemplate>
如果我对图像源路径进行硬编码,它也可以正常工作:
<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>
那么,为什么 TemplateBinding 在 ImageBrush 中会失败?
更新
通过推论(感谢克里斯的回答),可能的因素是:
-
ImageBrush继承 fromDependencyObjectrather than fromFrameworkElement -
TemplateBinding不支持像普通绑定那样的隐式类型转换(即字符串到ImageSource)
我仍然看不出这些点是如何连接的……
【问题讨论】:
标签: c# silverlight xaml windows-phone templatebinding