Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

c# - Creating a custom-shaped button with one rounded corner

I need to create a button in WPF that has a custom shape. Specifically, I want it to have rounded corners, like an ellipse. Here is a picture:

Only the black area should be a click target; the white area should be transparent.

How would I go about creating a button control in WPF that has such a custom shape? I know how to create a regular rectangular button, but not one with a rounded corner like this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use a ControlTemplate to achieve that:

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Black"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Path Fill="{TemplateBinding Background}"
                            Data="M 0,0 A 100,100 90 0 0 100,100 L 100,100 100,0" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Than you apply it to the button:

<Button Style="{StaticResource ButtonStyle}"/>

If you need some references to draw the "Path" check this MSDN link.

Update

To show the content you should use a ContentPresenter, something like this:

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Black"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid>
                        <Path Fill="{TemplateBinding Background}"
                            Data="M 0,0 A 100,100 90 0 0 100,100 L 100,100 100,0" />
                        <ContentPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                          HorizontalAlignment="{TemplateBinding HorizontalAlignment}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

In the button:

<Button Style="{StaticResource ButtonStyle}" Foreground="White">
        test
    </Button>

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...