Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can achieve this in a much cleaner way using a style and a couple of attached properties.</p> <p>The attached properties will store your specific information. The style will use these properties and build the look you want.</p> <p>The element will still be a button so the command and everything else will work.</p> <pre><code> public class ImageButton { public static ImageSource GetImage(DependencyObject obj) { return (ImageSource)obj.GetValue(ImageProperty); } public static void SetImage(DependencyObject obj, ImageSource value) { obj.SetValue(ImageProperty, value); } public static readonly DependencyProperty ImageProperty = DependencyProperty.RegisterAttached("Image", typeof(ImageSource), typeof(ImageButton), new UIPropertyMetadata(null)); public static String GetCaption(DependencyObject obj) { return (String)obj.GetValue(CaptionProperty); } public static void SetCaption(DependencyObject obj, String value) { obj.SetValue(CaptionProperty, value); } public static readonly DependencyProperty CaptionProperty = DependencyProperty.RegisterAttached("Caption", typeof(String), typeof(ImageButton), new UIPropertyMetadata(null)); } &lt;Style TargetType="{x:Type Button}" x:Key="ImageButton"&gt; &lt;Setter Property="ContentTemplate"&gt; &lt;Setter.Value&gt; &lt;DataTemplate&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;Image Source="{Binding Path=(local:ImageButton.Image), RelativeSource={RelativeSource AncestorType={x:Type Button}}}" /&gt; &lt;TextBlock Text="{Binding Path=(local:ImageButton.Caption), RelativeSource={RelativeSource AncestorType={x:Type Button}}}" Margin="2,0,0,0" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>You can then use this to declare buttons:</p> <pre><code> &lt;Button Style="{DynamicResource ImageButton}" local:ImageButton.Caption="Foo" local:ImageButton.Image="..." /&gt; </code></pre> <p>Note:</p> <p>I'm pretty sure it would be cleaner to go through the "Template" property and use a ControlTemplate and TemplateBindings, but that would mean re-creating the border and other stuff around your content, so if you are looking to just define a default "Content", my example would be the way to go, I think.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload