IV.
IV.

Reputation: 1233

Getting a templated button's command to work

I've used a control template to change the appearance of a button in a trivial way. It now looks different, but does not behave like a button. There are really two problems:

  1. The button's command is never executed
  2. After clicking on the button, it appears selected (i.e., the ellipse turns into an ugly blue rectangle)

Here's the general idea:

<Button Command="{x:Static commands:...}"
        CommandParameter="{Binding}">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Ellipse Fill="{Binding ...}"
                     .../>
        </ControlTemplate>
    </Button.Template>
</Button>

Upvotes: 0

Views: 357

Answers (3)

faith_jones
faith_jones

Reputation: 1

I had a similar problem with a custom templated button:

     <my:UniButton Command="{Binding MyCommand}"/>

The binding didn't work until adding a RelativeSource:

     <my:UniButton Command="{Binding MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=my:CustomPanel}}"/>

where CustomPanel is a control where my button lies.

Withal I had a simple button on the same panel, but it worked fine even without RelativeSource.

Upvotes: 0

IV.
IV.

Reputation: 1233

The problem turned out to be that Fill was bound to a value that could be null. If the Fill brush is null rather than transparent, then there's nothing to click and the command doesn't get executed. As Drew mentioned, with a solid fill, the button works correctly.

Takeaway lesson: if you want to hide your shape but still have it respond to user interaction, use a transparent brush, not a null brush.

Upvotes: 1

Drew Marsh
Drew Marsh

Reputation: 33379

  1. There's no reason this should be happening. I put together a test using ApplicationCommands.Copy and the command fired just fine. Could be your CommandBinding isn't working properly.
  2. I also didn't see this based on copying your sample XAML and just setting Fill="Green". You can try setting FocusVisualStyle="{x:Null}" on the Button.

Upvotes: 2

Related Questions