來看一個簡單的不以(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>
結果是: