我已经为ImageButton创建了一个自定义控件
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Local:ImageButton}">
<StackPanel Height="Auto" Orientation="Horizontal">
<Image Margin="0,0,3,0" Source="{Binding ImageSource}" />
<TextBlock Text="{TemplateBinding Content}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
ImageButton类看起来像
public class ImageButton : Button
{
public ImageButton() : base() { }
public ImageSource ImageSource
{
get { return base.GetValue(ImageSourceProperty) as ImageSource; }
set { base.SetValue(ImageSourceProperty, value); }
}
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("Source", typeof(ImageSource), typeof(ImageButton));
}
但是我无法将ImageSource绑定到图像: (此代码位于UI文件夹中,图像位于资源文件夹中)
<Local:ImageButton x:Name="buttonBrowse1" Width="100" Margin="10,0,10,0"
Content="Browse ..." ImageSource="../Resources/BrowseFolder.bmp"/>
但是,如果我拍摄一张简单的图像,如果指定了相同的源,则会显示该图像。 谁能告诉我应该做些什么?
答案 0 :(得分:2)
您需要使用Binding
替换ControlTemplate中的TemplateBinding
,就像您对Content属性所做的那样:
<Image Margin="0,0,3,0" Source="{TemplateBinding ImageSource}" />
此外,DependencyProperty的定义不正确。该字符串应为ImageSource
,而不仅仅是Source
:
DependencyProperty.Register("ImageSource", typeof(ImageSource), ...
我不知道这个名称冲突是否会导致任何问题,但至少强烈建议使用实际CLR属性的确切名称。
编辑:您还需要将样式的TargetType
更改为ImageButton
:
<Style TargetType="{x:Type Local:ImageButton}">