【问题标题】:Set different size or auto-resize for Path in StaticResource Canvas在静态资源画布中为路径设置不同的大小或自动调整大小
【发布时间】:2014-03-26 09:55:11
【问题描述】:

我的所有图标都使用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" />

有没有办法设置StaticResource 的大小或任何其他聪明的做法?

【问题讨论】:

    标签: c# .net wpf xaml canvas


    【解决方案1】:

    我想你可以把 Canvas 放在 &lt;ViewBox&gt; 里面,这样它会自动缩小。

    【讨论】:

    • Canvas 这里不需要。
    【解决方案2】:

    在这种情况下,Canvas 不是必需的,因此作为路径的属性 Canvas.LeftCanvas.Top。据我所知,它会自动添加生成这些路径的应用程序(例如 Blend)。此外,每个Path面板Canvas的性能保持成本非常高。

    你不需要存储资源的Width和Height,而是在Path中添加Stretch="Fill"

    <Button Width="30" Height="30">
        <Path Name="MyPath"              
              Fill="Bisque"
              Stretch="Fill"
              Data="..." />
    </Button>
    

    最重要的是 Data 在对象路径。您需要执行以下操作:

    在资源App.xaml&lt;Window.Resources&gt;等中添加带键的路径:

    <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 解决方案更易于使用
    猜你喜欢
    • 2011-11-15
    • 2021-04-06
    • 2014-07-29
    • 2011-01-08
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 2016-10-27
    相关资源
    最近更新 更多