Note that there are some explanatory texts on larger screens.

plurals
  1. POAttach ICommand in WPF UserControl
    text
    copied!<p>I implemented a simple button with an image in it:</p> <p></p> <pre><code> &lt;Button Command="{Binding ButtonCommand, ElementName=ImageButtonControl}"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;Image Source="{Binding ButtonImage, ElementName=ImageButtonControl}"/&gt; &lt;TextBlock Text="{Binding ButtonText, ElementName=ImageButtonControl}" Margin="2,0,0,0"/&gt; &lt;/StackPanel&gt; &lt;/Button&gt; </code></pre> <p></p> <p>As you can see, I expose a ButtonCommand property in order to be able to attach an ICommand to this UserControl:</p> <pre><code>public partial class ImageButton : UserControl { /// &lt;summary&gt; /// The dependency property that gets or sets the source of the image to render. /// &lt;/summary&gt; public static DependencyProperty ImageSourceProperty = DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(ImageButton)); public static DependencyProperty TextProperty = DependencyProperty.Register("ButtonText", typeof(string), typeof(ImageButton)); public static DependencyProperty ButtonCommandProperty = DependencyProperty.Register("ButtonCommand", typeof(ICommand), typeof(ImageButton)); public ImageButton() { this.DataContext = this; InitializeComponent(); } /// &lt;summary&gt; /// Gets or sets the button command. /// &lt;/summary&gt; public ICommand ButtonCommand { get { return (ICommand)GetValue(ImageButton.ButtonCommandProperty); } set { SetValue(ImageButton.ButtonCommandProperty, value); } } /// &lt;summary&gt; /// Gets or sets the button image. /// &lt;/summary&gt; public ImageSource ButtonImage { get { return (ImageSource)GetValue(ImageButton.ImageSourceProperty); } set { SetValue(ImageButton.ImageSourceProperty, value); } } /// &lt;summary&gt; /// Gets or sets the button text. /// &lt;/summary&gt; public string ButtonText { get { return (string)GetValue(ImageButton.TextProperty); } set { SetValue(ImageButton.TextProperty, value); } } } </code></pre> <p>Then when I declare my button it gives this:</p> <p><code>&lt;uc:ImageButton Grid.Row="1" Grid.Column="0" ButtonCommand="{Binding AttachContextCommand}" ButtonImage="{StaticResource AssociateImage}" ButtonText="Associer"/&gt;</code></p> <p>And badaboom, nothing never happen when I click on my ImageButton. When I replace the ImageButton with a simple button, the ICommand is called.</p> <p>I even tried to simply extends the Button class and bind an ICommand, but once again, it didn't work...</p> <p>Help appreciated !</p> <p>Thx.</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