문제

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?

도움이 되었습니까?

해결책

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}">
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top