如何使用DrawingBrush作为Window.Icon?

时间:2015-07-08 12:53:36

标签: c# wpf xaml

我有一个包含XAML图像的ResourceDictionary的dll:

  <DrawingBrush x:Key="imgFoo" ViewboxUnits="Absolute" Viewbox="0,0,128,128">
<DrawingBrush.Drawing>
  <GeometryDrawing Brush="#FF111111">
    <GeometryDrawing.Pen>
      <Pen LineJoin="Miter" StartLineCap="Square" EndLineCap="Square"/>
    </GeometryDrawing.Pen>
    <GeometryDrawing.Geometry>
      <PathGeometry Figures="M 56.5625 ... 64.03125 45.46875 z " FillRule="NonZero"/>
    </GeometryDrawing.Geometry>
  </GeometryDrawing>
</DrawingBrush.Drawing>

是否可以将此DrawingBrush用作Window.Icon?

使用staticresource或dynamicresource不起作用:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Icon="{DynamicResource imgFoo}">

我唯一发现的是使用像这样的Window.Resource:

    <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Icon="{DynamicResource imgFoo}">
  <Window.Resources>
<DrawingImage x:Key="imgFoo">
      <DrawingImage.Drawing>
      <GeometryDrawing Brush="#FF111111">
        <GeometryDrawing.Pen>
          <Pen LineJoin="Miter" StartLineCap="Square" EndLineCap="Square"/>
        </GeometryDrawing.Pen>
        <GeometryDrawing.Geometry>
          <PathGeometry Figures="M 56.5625 ... 64.03125 45.46875 z " FillRule="NonZero"/>
        </GeometryDrawing.Geometry>
      </GeometryDrawing>
      </DrawingImage.Drawing>
    </DrawingImage>
  </Window.Resources>

但是这只使用了dll文件中DrawingBrush的一部分,并创建了重复的xaml代码。

有关如何直接使用DrawingBrush的任何建议吗?

1 个答案:

答案 0 :(得分:2)

您可以将资源声明拆分为两部分,并分别声明GeometryDrawing和DrawingBrush:

Sub CheckCodes()
    Dim code As Range

    For Each code In Range("L2:L1000")
        If VBA.Right$(VBA.Trim$(code), 4) <> "8234" Then
            MsgBox "Non Standard Number Codes Found!  " & vbNewLine & "Check Number Codes  ", , "ADVISORY!"
            Exit Sub
        End If            
    Next code
End Sub

现在你可以在用作Window的图标的DrawingImage中直接重用GeometryDrawing:

<GeometryDrawing x:Key="imgFooDrawing" Brush="#FF111111">
    <GeometryDrawing.Pen>
        <Pen LineJoin="Miter" StartLineCap="Square" EndLineCap="Square"/>
    </GeometryDrawing.Pen>
    <GeometryDrawing.Geometry>
        <PathGeometry Figures="M10,64 L64,10 118,64 64,118Z" FillRule="NonZero"/>
    </GeometryDrawing.Geometry>
</GeometryDrawing>
<DrawingBrush x:Key="imgFoo" ViewboxUnits="Absolute" Viewbox="0,0,128,128"
              Drawing="{StaticResource imgFooDrawing}">
</DrawingBrush>

如果您无法更改资源DLL,可以将DrawingImage的Drawing属性绑定到DrawingBrush的Drawing属性。

然而,这将需要一个丑陋的解决方法,因为您不能使用DynamicResource作为绑定源。您可以将Window的Tag属性设置为DrawingBrush,然后创建RelativeSource / FindAncestor绑定:

<Window.Icon>
    <DrawingImage Drawing="{DynamicResource imgFooDrawing}"/>
</Window.Icon>