1

我为 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"/>

但是,如果我拍摄一个简单的图像,如果指定了相同的来源,它就会显示出来。谁能告诉我该怎么办?

4

1 回答 1

2

您需要将BindingControlTemplate 中的 替换为 a TemplateBinding,就像对 Content 属性所做的那样:

<Image Margin="0,0,3,0" Source="{TemplateBinding ImageSource}" />

此外,您的 DependencyProperty 的定义不正确。该字符串应该读取ImageSource,而不仅仅是Source

DependencyProperty.Register("ImageSource", typeof(ImageSource), ...

我不知道这个名称冲突是否/在哪里会导致任何问题,但至少强烈建议使用实际 CLR 属性的确切名称。

编辑:您还必须将TargetType您的 Style 更改为您的ImageButton

<Style TargetType="{x:Type Local:ImageButton}">
于 2010-04-28T10:11:31.363 回答