WPFで自由形状のユーザーコントロールを作成するには

WPFのパス要素とジオメトリデータを使用して形状を定義することで、自由形式のユーザーコントロールを作成できます。以下はその簡単な例です。

  1. カスタムシェイプコントロール(たとえば、CustomShapeControl.xaml)などの新しいWPFユーザーコントロールを作成します。
  2. XAML ファイルに Grid をルート要素として追加し、Path 要素を追加します。以下に例を示します。
<UserControl x:Class="YourNamespace.CustomShapeControl"
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:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Path x:Name="customShapePath" Fill="Red" Stroke="Black" StrokeThickness="1"/>
</Grid>
</UserControl>
  1. CustomShapeControl.xaml.csのコードファイルでGeometryデータを使用してカスタムシェイプを定義する。例:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace YourNamespace
{
public partial class CustomShapeControl : UserControl
{
public CustomShapeControl()
{
InitializeComponent();
// 创建自定义形状的Geometry对象
PathGeometry geometry = new PathGeometry();
PathFigure figure = new PathFigure();
// 添加自定义形状的路径
figure.StartPoint = new Point(0, 0);
figure.Segments.Add(new LineSegment(new Point(100, 100), true));
figure.Segments.Add(new ArcSegment(new Point(200, 0), new Size(100, 100), 0, false, SweepDirection.Clockwise, true));
figure.Segments.Add(new LineSegment(new Point(0, 0), true));
// 将Geometry对象设置为Path元素的Data属性
geometry.Figures.Add(figure);
customShapePath.Data = geometry;
}
}
}

この例では、直線と弧からなるカスタム形状を作成し、Path要素のData属性として設定しています。形状のパスは自分のニーズに合わせて追加・変更できます。

たとえユーザーコントロールをカスタマイズした場合でも、普通のユーザーコントロールと同様にサイズや位置を外部から設定できます。例えば:

<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourNamespace"
Title="MainWindow" Height="450" Width="800">
<Grid>
<local:CustomShapeControl Width="200" Height="200" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>

上の例では、CustomShapeControlの大きさが 200×200 に設定され、親の Grid の中心に水平垂直に配置されています。

bannerAds