代码之家  ›  专栏  ›  技术社区  ›  Archie

发出绑定图像源依赖项属性

  •  1
  • Archie  · 技术社区  · 15 年前

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

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

    1 回复  |  直到 15 年前
        1
  •  2
  •   gehho    15 年前

    你需要更换 Binding 在控件模板中 TemplateBinding ,就像您对内容属性所做的那样:

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

    此外,您的家属财产的定义不正确。字符串应为 ImageSource 而不是仅仅 Source :

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

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

    编辑: 你还必须改变 TargetType 你的风格 ImageButton :

    <Style TargetType="{x:Type Local:ImageButton}">