How to make the contents of a round-cornered border be also round-cornered?

后端 未结 7 1637
天涯浪人
天涯浪人 2020-11-27 14:11

I have a border element with rounded corners containing a 3x3 grid. The corners of the grid are sticking out of the border. How can I fix that? I tried using ClipToBounds bu

相关标签:
7条回答
  • 2020-11-27 14:58

    Using @Andrew Mikhailov's solution, you can define a simple class, which makes defining a VisualBrush for each affected element manually unnecessary:

    public class ClippedBorder : Border
    {
        public ClippedBorder() : base()
        {
            var e = new Border()
            {
                Background = Brushes.Black,
                SnapsToDevicePixels = true,
            };
            e.SetBinding(Border.CornerRadiusProperty, new Binding()
            {
                Mode = BindingMode.OneWay,
                Path = new PropertyPath("CornerRadius"),
                Source = this
            });
            e.SetBinding(Border.HeightProperty, new Binding()
            {
                Mode = BindingMode.OneWay,
                Path = new PropertyPath("ActualHeight"),
                Source = this
            });
            e.SetBinding(Border.WidthProperty, new Binding()
            {
                Mode = BindingMode.OneWay,
                Path = new PropertyPath("ActualWidth"),
                Source = this
            });
    
            OpacityMask = new VisualBrush(e);
        }
    }
    

    To test this, just compile the following two samples:

    <!-- You should see a blue rectangle with rounded corners/no red! -->
    <Controls:ClippedBorder
        Background="Red"
        CornerRadius="10"
        Height="425"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Width="425">
        <Border Background="Blue">
        </Border>
    </Controls:ClippedBorder>
    
    <!-- You should see a blue rectangle with NO rounded corners/still no red! -->
    <Border
        Background="Red"
        CornerRadius="10"
        Height="425"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Width="425">
        <Border Background="Blue">
        </Border>
    </Border>
    
    0 讨论(0)
提交回复
热议问题