Web Dev
Web Dev

Reputation: 2937

WPF togglebutton

I've got an issue with a custom WPF button - whenever I click on it, it receives a click event but does not seem to get toggled (does not stay down when I click on another button). I've tried everything I can think of and still can't get it to work.

One weird thing that I have noticed though is that when I put a breakpoint in the MouseDown handler and just hit F5 to continue at that point, the button gets toggled and stays down. This leads me to believe that this is some sort of focus issue?

<ToggleButton Name="ToggleButton" PreviewMouseDown="ToggleButton_MouseDown_1" IsThreeState="False">
    <StackPanel Orientation="Vertical">
        <Label Content="Single" FontSize="15" FontWeight="Medium"/>
        <Label Content="Speaker"/>
    </StackPanel>
</ToggleButton>

private void ToggleButton_MouseDown_1(object sender, MouseButtonEventArgs e)
{
    ToggleButton.IsChecked = !ToggleButton.IsChecked;
}

    private void ToggleButton_MouseDown_1(object sender, MouseButtonEventArgs e)
{
    ToggleButton.IsChecked = !ToggleButton.IsChecked;
}

Help? :)

Upvotes: 0

Views: 6872

Answers (2)

bwall
bwall

Reputation: 1060

It sounds like you want the functionality of a set of radio buttons, but the look of a bunch of toggle buttons. In cases like these, using the inherited Control.Template property is really handy:

In your page resources, you can add:

<Style TargetType="RadioButton">
    <Setter Property="Template">
        <Setter.Value>
           <ContentTemplate>
               <ToggleButton Content="{TemplateBinding Content}" IsChecked="{TemplateBinding IsChecked}"/>
           </ContentTemplate>
        </Setter.Value>
    </Setter>
</Style>

And then in your code:

<RadioButton Content="MyContent" GroupName="MyGroup"/>

This should make an object that looks like a toggle button, but deselects when you select something from the same group, like a RadioButton. You can further modify the ToggleButton in the Template until you get the look that you want.

Upvotes: 2

Iain
Iain

Reputation: 2550

As @Nick said in his comment, just remove your event handler PreviewMouseDown="ToggleButton_MouseDown_1" completely and it should work just fine.

If this is not the case you must have some other code which is causing the issue.

Upvotes: 2

Related Questions