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 フォルダーにあり、画像は Resource フォルダーにあります)。

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

しかし、単純な画像を撮ると、同じソースが指定されていれば表示されます。誰が何をすべきか教えてもらえますか?

4

1 に答える 1

2

Contentプロパティの場合と同様に、BindingControlTemplateのををに置き換える必要があります。TemplateBinding

<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}">
于 2010-04-28T10:11:31.363 に答える