Archie
Archie

Reputation: 2579

Issue binding Image Source dependency property

I have created a custom control for ImageButton as

<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 class looks like

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));
    }

However I'm not able to bind the ImageSource to the image as: (This code is in UI Folder and image is in Resource folder)

  <Local:ImageButton x:Name="buttonBrowse1" Width="100" Margin="10,0,10,0"
 Content="Browse ..." ImageSource="../Resources/BrowseFolder.bmp"/>

But if i take a simple image it gets displayed if same source is specified. Can anyone tell me what shall be done?

Upvotes: 2

Views: 9085

Answers (1)

gehho
gehho

Reputation: 9238

You need to replace the Binding in your ControlTemplate by a TemplateBinding, just as you did for the Content property:

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

Furthermore, the definition of your DependencyProperty is not correct. The string should read ImageSource instead of just Source:

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

I do not know whether/where this name conflict causes any problems, but at least it is highly recommended to use the exact name of the actual CLR property.

EDIT: You will also have to change the TargetType of your Style to your ImageButton:

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

Upvotes: 4

Related Questions