来看一个简单的不以(0,0)开始的Path:
<Path Data="M 50,50 l 10,10 M 100,20 l -10,-10" />
结果是:
此时Path的Stretch的值是默认的None,因此无论将当前Path的Width和Height设置成多大,Path中的线始终保持如上大小。
因此如果想放大或缩小Path的话,需要将Stretch设置成Fill,Uniform或者UniformToFill。但是注意此时Path的空白区域会别截掉,如下XAML:
<!-- Stretch = Fill 或 Uniform 或 UniformFill-->
<Path Data="M 50,50 l 10,10 M 100,20 l -10,-10" Stretch="Fill"/>
预览结果是:
可以看到,此时Path的大小全部实际绘图区域的大小,而不会将一些起始点的空白区域考虑进去。
当然如果你想保留空白区域(即按照Path.Stretch=None的图形进行缩放):
可以把Path放在Canvas里,并手动调整在Canvas的位置。
还有一种更好的方法就是把Path放在ViewBox里,然后调整ViewBox的属性就可以了。
比较结果是这样:
完整XAML
<Window x:Class="TEX.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Mgen" Height="300" Width="300">
<Window.Resources>
<Style TargetType="{x:Type Path}">
<Setter Property="Stroke" Value="Red" />
<Setter Property="StrokeThickness" Value="1" />
</Style>
</Window.Resources>
<ListBox HorizontalContentAlignment="Center">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Orange"
BorderThickness="1">
<ContentPresenter Content="{Binding}" />
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsSource>
<x:Array Type="{x:Type FrameworkElement}">
<Path Data="M 50,50 l 10,10 M 100,20 l -10,-10" />
<Path Data="M 50,50 l 10,10 M 100,20 l -10,-10"
Stretch="Fill" Height="100" Width="200"/>
<Viewbox Stretch="Fill" Height="100" Width="200">
<Path Data="M 50,50 l 10,10 M 100,20 l -10,-10" />
</Viewbox>
</x:Array>
</ListBox.ItemsSource>
</ListBox>
</Window>
另外注意:Line类和闭合的Path也是这样的,比如:
<Window.Resources>
<Style TargetType="{x:Type Path}">
<Setter Property="Stroke" Value="Red" />
<Setter Property="StrokeThickness" Value="1" />
</Style>
<Style TargetType="{x:Type Line}">
<Setter Property="Stroke" Value="Red" />
<Setter Property="StrokeThickness" Value="1" />
</Style>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel>
<Path Data="M 50,50 l 50,50 h 100 Z" />
<Path Data="M 50,50 l 50,50 h 100 Z" Stretch="Fill" Height="100"></Path>
<Viewbox>
<Path Data="M 50,50 l 50,50 h 100 Z" />
</Viewbox>
</StackPanel>
<StackPanel Grid.Column="1">
<Line X1="50" Y1="50" X2="100" Y2="100" />
<Line X1="50" Y1="50" X2="100" Y2="100" Stretch="Fill"/>
<Viewbox Stretch="Fill">
<Line X1="50" Y1="50" X2="100" Y2="100" />
</Viewbox>
</StackPanel>
</Grid>
结果是: