我为 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 绑定(bind)到图像,如下所示: (此代码位于 UI 文件夹中,图像位于 Resource 文件夹中)
<Local:ImageButton x:Name="buttonBrowse1" Width="100" Margin="10,0,10,0"
Content="Browse ..." ImageSource="../Resources/BrowseFolder.bmp"/>
但是,如果我拍摄一个简单的图像,如果指定了相同的源,它就会显示出来。 谁能告诉我该怎么办?
最佳答案
您需要将 ControlTemplate 中的 Binding
替换为 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}">
关于wpf - 问题绑定(bind)图像源依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2728449/