如何创建可容纳其他UI元素的圆形Border

像这样:



有一些简单的方法可以达到类似的效果吗?

最佳答案

这适用于MultiValueConverter

public class CircleMarginConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var width = (double)values[0];
        var height = (double)values[1];
        var diagonal = Math.Sqrt(width * width + height * height);
        var horzmargin = (diagonal - width) / 2;
        var vertmargin = (diagonal - height) / 2;
        return new Thickness(horzmargin,vertmargin,horzmargin,vertmargin);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}


使用以下用户控件:

<UserControl x:Class="CircleBorderTest.CircleBorder"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:CircleBorderTest"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.ContentTemplate>
        <DataTemplate DataType="UserControl">
            <DataTemplate.Resources>
                <local:CircleMarginConverter x:Key="CircleMarginConverter"/>
            </DataTemplate.Resources>
            <Grid VerticalAlignment="Center" HorizontalAlignment="Center">
                <ContentPresenter Content="{TemplateBinding Content}">
                    <ContentPresenter.Margin>
                        <MultiBinding Converter="{StaticResource CircleMarginConverter}">
                            <Binding Path="ActualWidth" RelativeSource="{RelativeSource Self}"/>
                            <Binding Path="ActualHeight" RelativeSource="{RelativeSource Self}"/>
                        </MultiBinding>
                    </ContentPresenter.Margin>
                </ContentPresenter>
                <Ellipse HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stroke="Red" StrokeThickness="1px"/>
            </Grid>
        </DataTemplate>
    </UserControl.ContentTemplate>
</UserControl>


和这样使用:

<Window x:Class="CircleBorderTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:CircleBorderTest"
        Title="MainWindow" Height="350" Width="525">
    <local:CircleBorder>
        yeah
    </local:CircleBorder>
</Window>


随内容调整大小。实际上,您可以在任何您喜欢的ContentControl上使用此样式。

关于wpf - 如何在UI元素周围创建圆形边框?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5178843/

10-14 04:13