为什么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
内部失败呢?
更新
通过推论(感谢Chris的回答),可能的因素有:
ImageBrush
继承FrameworkElement
TemplateBinding
不像普通绑定那样支持隐式类型转换(即string- that )但我还是不明白这些点是怎么联系起来的.
发布于 2014-03-02 22:23:30
这里有个解决办法。奇怪的是,使用RelativeSource TemplatedParent
绑定而不是TemplateBinding
解决了这个问题。
<ImageBrush ImageSource="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Icon}" />
理论上这是完全相同的约束..。谁知道呢?什么都行。
https://stackoverflow.com/questions/22134281
复制相似问题