在StaticResource Canvas中,为路径设置不同的尺寸或自动调整大小

3
我将使用ResourceDictionary来管理所有的图标,示例如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Canvas x:Key="Icon.Refresh"
            Width="32" Height="32"
            Clip="F1 M 0,0L 32,0L 32,32L 0,32L 0,0">
        <Path Width="28" Height="28"
              Canvas.Left="2" Canvas.Top="2"
              Stretch="Fill"
              Data="..." /> 
    </Canvas>
 </ResourceDictionary>

实际上的XAML代码:

<Button Content="{StaticResource Icon.Refresh}"
        Height="40" 
        Width="40" />

这对大多数按钮都很有效。但当我想在较小的按钮上使用它时,它会溢出该按钮:

<Button Content="{StaticResource Icon.Refresh}"
        Height="30" 
        Width="30" />

ReloadButton

有没有一种方法可以设置StaticResource的大小或者其他聪明的做法呢?

2个回答

5

我认为你可以将Canvas放在<ViewBox>内部,这样它就会自动缩小。


这里不需要Canvas。 - Anatoliy Nikolaev

3
在这种情况下,Canvas不是必需的,因此对于Path,也不需要使用Canvas.LeftCanvas.Top属性。据我所知,它会自动添加应用程序(例如Blend),生成这些Path。此外,为了性能考虑,保留每个Path面板的Canvas非常昂贵。
您不需要存储资源的宽度和高度,而是将Stretch="Fill"添加到Path中即可:
<Button Width="30" Height="30">
    <Path Name="MyPath"              
          Fill="Bisque"
          Stretch="Fill"
          Data="..." />
</Button>

最重要的是对象路径中涉及到数据(Data)。您需要执行以下操作:

在资源文件App.xaml<Window.Resources>等中,添加带有键名的Path:

<Path x:Key="MyPath" Data="F1 M 0,0L ..." />

Style或其他类似的地方使用如下:

<Path x:Name="MyPathButton"
      ...
      Fill="{StaticResource ButtonBackground}" 
      Data="{Binding Source={StaticResource MyPath}, Path=Data}" />

或者这样做:将数据放入 Geometry 中:
<Geometry x:Key="MagnifierIconGeometry">M44,12 C32,12 22,22 22,34 22,46 32,56 44,56 56,56 66,46 66,34 66,22 56,12 44,12z M44,0 C63,0 78,15 78,34 78,53 63,68 44,68 40,68 36.5,67.5 33,66 L32.5,66 14,90 0,79.5 18,55.5 17,55 C13,49 10,42 10,34 10,15 25,0 44,0z</Geometry>

使用方法如下:

<Path Data="{StaticResource MagnifierIconGeometry}" 
      Fill="Black"
      Stretch="Fill" />

你的答案在技术上是正确的,但是使用ViewBox解决方案更加容易。 - Staeff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接