关于自定义Button继承Button,扩展属性来设置自定义Button背景的问题
求助
自定义类继承Button,添加自定义属性BackgroundSource,通过模板控制这个属性作为按钮的Background,但背景没有正常显示。
自定义类BackgroundButton继承Button
class BackgroundButton:System.Windows.Controls.Button
{
public string BackgroundSource(此处类型定义为ImageSource问题一样,不报错,但不显示背景)
{
get { return (string)GetValue(BackgroundSourceProperty); }
set { SetValue(BackgroundSourceProperty, value); }
}
// Using a DependencyProperty as the backing store for TestProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BackgroundSourceProperty =
DependencyProperty.Register("BackgroundSource", typeof(string), typeof(BackgroundButton));
}
----------------------------------------
通过样式控制这个类的显示
<Style TargetType="{x:Type local:BackgroundButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:BackgroundButton}">
<Grid>
<Border x:Name ="OuterRing">
<Border.Background>
<ImageBrush ImageSource="{TemplateBinding BackgroundSource}"/>(此处不报错,但背景显示不出来,如果写死个路径就可以)
</Border.Background>
</Border>
</Grid>
-----------------------------------------
XAML代码中使用
<local:BackgroundButton BackgroundSource="/Resource/DialPad/phoneDial.png" Width="98"(此处也没有任何异常)
通过如上设置,其它功能都正常,就是背景显示不出来。
求问题原因及解决方案,谢谢。
[解决办法]
public BackgroundButton()
{
this.DefaultStyleKey = typeof(BackgroundButton);
}
[解决办法]
<ImageBrush ImageSource="{Binding Path=BackgroundSource,RelativeSource={RelativeSource Mode=TemplatedParent}}"/>