wpf 如何使圆角边框的内容也是圆角的?

1mrurvl1  于 2023-04-07  发布在  其他
关注(0)|答案(7)|浏览(262)

我有一个包含3x3网格的圆角边框元素。网格的角伸出边框。我如何解决这个问题?我尝试使用ClipToBounds,但没有任何结果。感谢您的帮助

hec6srdp

hec6srdp1#

以下是Jobi提到的这个线程的亮点

  • 没有一个装饰器(即Border)或布局面板(即Stackpanel)具有这种开箱即用的行为。
  • ClipToBounds用于布局。ClipToBounds不会阻止元素绘制到其边界之外;它只是防止子元素的布局“溢出”。此外,ClipToBounds=True对于大多数元素来说是不需要的,因为它们的实现不允许它们的内容布局溢出。最值得注意的例外是Canvas。
  • 最后,Border将圆角视为其布局边界内的绘图。

下面是一个继承自Border的类的实现,并实现了适当的功能:

/// <Remarks>
    ///     As a side effect ClippingBorder will surpress any databinding or animation of 
    ///         its childs UIElement.Clip property until the child is removed from ClippingBorder
    /// </Remarks>
    public class ClippingBorder : Border {
        protected override void OnRender(DrawingContext dc) {
            OnApplyChildClip();            
            base.OnRender(dc);
        }

        public override UIElement Child 
        {
            get
            {
                return base.Child;
            }
            set
            {
                if (this.Child != value)
                {
                    if(this.Child != null)
                    {
                        // Restore original clipping
                        this.Child.SetValue(UIElement.ClipProperty, _oldClip);
                    }

                    if(value != null)
                    {
                        _oldClip = value.ReadLocalValue(UIElement.ClipProperty);
                    }
                    else 
                    {
                        // If we dont set it to null we could leak a Geometry object
                        _oldClip = null;
                    }

                    base.Child = value;
                }
            }
        }

        protected virtual void OnApplyChildClip()
        {
            UIElement child = this.Child;
            if(child != null)
            {
                _clipRect.RadiusX = _clipRect.RadiusY = Math.Max(0.0, this.CornerRadius.TopLeft - (this.BorderThickness.Left * 0.5));
                _clipRect.Rect = new Rect(Child.RenderSize);
                child.Clip = _clipRect;
            }
        }

        private RectangleGeometry _clipRect = new RectangleGeometry();
        private object _oldClip;
    }
d5vmydt9

d5vmydt92#

纯XAML:

<Border CornerRadius="30" Background="Green">
    <Border.OpacityMask>
        <VisualBrush>
            <VisualBrush.Visual>
                <Border 
                    Background="Black"
                    SnapsToDevicePixels="True"
                    CornerRadius="{Binding CornerRadius, RelativeSource={RelativeSource AncestorType=Border}}"
                    Width="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Border}}"
                    Height="{Binding ActualHeight, RelativeSource={RelativeSource AncestorType=Border}}"
                    />
            </VisualBrush.Visual>
        </VisualBrush>
    </Border.OpacityMask>
    <TextBlock Text="asdas das d asd a sd a sda" />
</Border>

**更新:**找到了一个更好的方法来达到同样的效果。现在您也可以将 Border 替换为任何其他元素。

<Grid>
    <Grid.OpacityMask>
        <VisualBrush Visual="{Binding ElementName=Border1}" />
    </Grid.OpacityMask>
    <Border x:Name="Border1" CornerRadius="30" Background="Green" />
    <TextBlock Text="asdas das d asd a sd a sda" />
</Grid>

lfapxunr

lfapxunr3#

正如Micah提到的,ClipToBounds不能与Border.ConerRadius一起工作。
UIElement.Clip属性,Border支持该属性作为子元素。
如果你知道边界的确切大小,那么下面是解决方案:

<Border Background="Blue" CornerRadius="3" Height="100" Width="100">
      <Border.Clip>
        <RectangleGeometry RadiusX="3" RadiusY="3" Rect="0,0,100,100"/>
      </Border.Clip>
      <Grid Background="Green"/>
</Border>

如果大小未知或者是动态的,那么可以使用Converter for Border.Clip。参见解决方案here

ulydmbyx

ulydmbyx4#

所以我只是偶然发现了这个解决方案,然后按照Jobi提供的msdn论坛链接,花了20分钟编写了我自己的ClippingBorder控件。
然后我意识到CornerRadius属性类型不是double,而是System.Windows.CornerRaduis,它接受4个double,每个角一个。
所以我现在要列出另一个替代解决方案,这将很可能满足大多数人的要求,他们将在未来偶然发现这篇文章。
假设你有一个XAML,它看起来像这样:

<Border CornerRadius="10">
    <Grid>
        ... your UI ...
    </Grid>
</Border>

问题是Grid元素的背景会溢出圆角。确保<Grid>的背景是透明的,而不是将相同的画笔分配给<Border>元素的“Background”属性。不再溢出圆角,也不需要一大堆CustomControl代码。
理论上,客户区仍然有可能绘制超过角落的边缘,但您可以控制该内容,因此作为开发人员,您应该能够有足够的填充,或者确保边缘旁边的控件的形状是适当的(在我的情况下,我的按钮是圆形的,所以非常适合角落,没有任何问题)。

7d7tgy0s

7d7tgy0s5#

使用@Andrew Mikhailov的解决方案,您可以定义一个简单的类,这使得为每个受影响的元素手动定义VisualBrush变得不必要:

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);
    }
}

要测试这一点,只需编译以下两个示例:

<!-- 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>
rpppsulh

rpppsulh6#

将网格变小或边框变大。以便边框元素完全包含网格。
或者,看看你是否可以使网格的背景透明,这样“突出”就不明显了。

**更新:**哎呀,没有注意到这是一个WPF问题。我不熟悉。这是一般的HTML/CSS建议。也许它会有所帮助...

nwlqm0z1

nwlqm0z17#

我不喜欢使用自定义控件。创建了一个行为代替。

using System.Linq;
using System.Windows;
using System.Windows.Interactivity;

/// <summary>
/// Base class for behaviors that could be used in style.
/// </summary>
/// <typeparam name="TComponent">Component type.</typeparam>
/// <typeparam name="TBehavior">Behavior type.</typeparam>
public class AttachableForStyleBehavior<TComponent, TBehavior> : Behavior<TComponent>
        where TComponent : System.Windows.DependencyObject
        where TBehavior : AttachableForStyleBehavior<TComponent, TBehavior>, new()
{
#pragma warning disable SA1401 // Field must be private.

    /// <summary>
    /// IsEnabledForStyle attached property.
    /// </summary>
    public static DependencyProperty IsEnabledForStyleProperty =
        DependencyProperty.RegisterAttached("IsEnabledForStyle", typeof(bool),
        typeof(AttachableForStyleBehavior<TComponent, TBehavior>), new FrameworkPropertyMetadata(false, OnIsEnabledForStyleChanged));

#pragma warning restore SA1401

    /// <summary>
    /// Sets IsEnabledForStyle value for element.
    /// </summary>
    public static void SetIsEnabledForStyle(UIElement element, bool value)
    {
        element.SetValue(IsEnabledForStyleProperty, value);
    }

    /// <summary>
    /// Gets IsEnabledForStyle value for element.
    /// </summary>
    public static bool GetIsEnabledForStyle(UIElement element)
    {
        return (bool)element.GetValue(IsEnabledForStyleProperty);
    }

    private static void OnIsEnabledForStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        UIElement uie = d as UIElement;

        if (uie != null)
        {
            var behColl = Interaction.GetBehaviors(uie);
            var existingBehavior = behColl.FirstOrDefault(b => b.GetType() ==
                  typeof(TBehavior)) as TBehavior;

            if ((bool)e.NewValue == false && existingBehavior != null)
            {
                behColl.Remove(existingBehavior);
            }
            else if ((bool)e.NewValue == true && existingBehavior == null)
            {
                behColl.Add(new TBehavior());
            }
        }
    }
}
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

/// <summary>
/// Behavior that creates opacity mask brush.
/// </summary>
internal class OpacityMaskBehavior : AttachableForStyleBehavior<Border, OpacityMaskBehavior>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        var border = new Border()
        {
            Background = Brushes.Black,
            SnapsToDevicePixels = true,
        };

        border.SetBinding(Border.CornerRadiusProperty, new Binding()
        {
            Mode = BindingMode.OneWay,
            Path = new PropertyPath("CornerRadius"),
            Source = AssociatedObject
        });

        border.SetBinding(FrameworkElement.HeightProperty, new Binding()
        {
            Mode = BindingMode.OneWay,
            Path = new PropertyPath("ActualHeight"),
            Source = AssociatedObject
        });

        border.SetBinding(FrameworkElement.WidthProperty, new Binding()
        {
            Mode = BindingMode.OneWay,
            Path = new PropertyPath("ActualWidth"),
            Source = AssociatedObject
        });

        AssociatedObject.OpacityMask = new VisualBrush(border);
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        AssociatedObject.OpacityMask = null;
    }
}
<Style x:Key="BorderWithRoundCornersStyle" TargetType="{x:Type Border}">
    <Setter Property="CornerRadius" Value="50" />
    <Setter Property="behaviors:OpacityMaskBehavior.IsEnabledForStyle" Value="True" />
</Style>

相关问题