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

后端 未结 7 1736
天涯浪人
天涯浪人 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:

    
    
        
        
    
    
    
    
        
        
    
    

提交回复
热议问题