要“重复使用”形状,您可以将样式定义为App.xaml
。例如:
你App.xaml
:
<Application x:Class="WpfApp4.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp4"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style x:Key="YellowEllipseWithBlackBorder" TargetType="Ellipse">
<Setter Property="Fill" Value="Yellow" />
<Setter Property="Width" Value="100" />
<Setter Property="Height" Value="100" />
<Setter Property="StrokeThickness" Value="5" />
<Setter Property="Stroke" Value="Black" />
</Style>
</Application.Resources>
</Application>
你MainWindow.xaml
:
<Window x:Class="WpfApp4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Ellipse Style="{StaticResource YellowEllipseWithBlackBorder}" />
<Ellipse Style="{StaticResource YellowEllipseWithBlackBorder}" />
<Ellipse Style="{StaticResource YellowEllipseWithBlackBorder}" />
</StackPanel>
</Grid>
</Window>
结果:
正如你所看到的,你应该定义一个样式为你塑造和t母鸡从窗口这个语法应用它:<Ellipse Style="{StaticResource YellowEllipseWithBlackBorder}" />
如果您希望以编程方式做同样的,你可以在前面的例子中定义形状的风格一样,然后在窗口的后台代码:
public partial class MainWindow : Window
{
private StackPanel _stackPanel;
public MainWindow()
{
InitializeComponent();
_stackPanel = new StackPanel()
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
Content = _stackPanel;
AddEllipse();
AddEllipse();
AddEllipse();
}
public void AddEllipse()
{
var ellipse = new Ellipse()
{
Style = FindResource("YellowEllipseWithBlackBorder") as Style
};
_stackPanel.Children.Add(ellipse);
}
}
要绘制自定义形状,你可以使用Polygon
控制,您可以在其中定义形状的点,例如:
public void AddPolygon()
{
var polygon = new Polygon()
{
Fill = new SolidColorBrush(Colors.Red),
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 2.0
};
polygon.Points.Add(new Point(0, 0));
polygon.Points.Add(new Point(10, 0));
polygon.Points.Add(new Point(5, -10));
_stackPanel.Children.Add(polygon);
}
结果:
画一些曲线,你可以使用Path
控制与BezierSegment
,例如:
public void AddPath()
{
var canvas = new Canvas();
var path = new Path()
{
Fill = new SolidColorBrush(Colors.Red),
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 2.0
};
var geometry = new PathGeometry();
geometry.Figures.Add(new PathFigure(
new Point(0, 0),
new List<BezierSegment>()
{
new BezierSegment(
new Point(0, 0),
new Point(100, 0),
new Point(50, -100),
true)
},
false));
path.Data = geometry;
canvas.Children.Add(path);
_stackPanel.Children.Add(canvas);
}
何不你是不是在寻找和开始一些事情并回到你正面临的确切问题?另请检查:[我如何问一个好问题](https://stackoverflow.com/help/how-to-ask) –