この Stackoverflow questionの助けを借りて、ボタン用の独自のカスタム コントロールを作成しようとしました
しかし、Button コントロールは、画像とテキスト以外は空です。
他に何も指定されていない場合、デフォルトの動作を使用する可能性はありますか?
ほぼ適合するものがすでに存在する場合、ボタン全体を書き直したくありません。ImageSource とテキスト、およびすべてではなく一部のスタイリングを追加したかっただけです。
これが私が持っているものです、おそらく私はいくつかの間違いを犯しました.
クラス定義:
public class MyImageButton : Button
{
static MyImageButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyImageButton), new FrameworkPropertyMetadata(typeof(MyImageButton)));
}
public ImageSource ImageSource
{
get { return (ImageSource)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(MyImageButton), new UIPropertyMetadata(null));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyImageButton), new UIPropertyMetadata(null));
}
generic.xaml から
<Style TargetType="{x:Type local:MyImageButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyImageButton}">
<StackPanel Height="Auto" Orientation="Horizontal">
<Image Source="{TemplateBinding ImageSource}" Width="24" Height="24" Stretch="Fill" />
<TextBlock Text="{TemplateBinding Text}" HorizontalAlignment="Left" Foreground="Black" FontWeight="Bold" Margin="5,0,0,0" VerticalAlignment="Center" FontSize="12" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
そして最後に、メインウィンドウ xaml での使用法
<ctrl:MyImageButton ImageSource="SomeImage.png" Text="BlaBlubb" Height="100" Width="120" Click="CheckClick" />