How do I create a WPF rounded container that clips children?

前端 未结 1 1489
时光说笑
时光说笑 2021-01-19 22:11

The following piece of code is supposed to draw a menu bar inside a rounded container. You\'ll notice that the bottom is rounded, but the corners of the menu aren\'t. I fo

相关标签:
1条回答
  • 2021-01-19 22:47

    Chris Cavanagh has a blog post about rounding controls. It should help you achieve what you want.

    Edit: Below is the code from that blog.

    <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="Black">
        <!-- Rounded yellow border -->
        <Border BorderThickness="3" BorderBrush="Yellow" CornerRadius="10" Padding="2" HorizontalAlignment="Center" VerticalAlignment="Center">
            <Grid>
                <!-- Rounded mask (stretches to fill Grid) -->
                <Border Name="mask" Background="White" CornerRadius="7"/>
                <!-- Main content container -->
                <StackPanel>
                    <!-- Use a VisualBrush of 'mask' as the opacity mask -->
                    <StackPanel.OpacityMask>
                        <VisualBrush Visual="{Binding ElementName=mask}"/>
                    </StackPanel.OpacityMask>
                    <!-- Any content -->
                    <Image Source="https://chriscavanagh.files.wordpress.com/2006/12/chriss-blog-banner.jpg"/>
                    <Rectangle Height="50" Fill="Red"/>
                    <Rectangle Height="50" Fill="White"/>
                    <Rectangle Height="50" Fill="Blue"/>
                </StackPanel>
            </Grid>
        </Border>
    </Page>
    

    All it does is include a ‘mask’ Border element as a sibling of the content you want to clip. In the content it uses a VisualBrush bound to that mask. The mask will be automatically sized to your content, so it’s a nice "set and forget" solution

    0 讨论(0)
提交回复
热议问题