2009-02-02 42 views
3

似乎遇到很多問題,使用XAML/WPF做簡單的事情 - 我使用Rectangle和Ellipse等形狀創建了一些基於XAML的圖像,以創建需要使用其他應用程序部分的圖標 - 但我似乎無法找到如何做到這一點 - 我似乎能夠在資源字典中存儲畫布,但無法在任何其他窗口中使用它。這是如何完成的 - 這些都是簡單的圖像,我想在整個項目中使用兩三個形狀!
圖像也必須可調整大小 - 我知道如何存儲路徑,但是這些形狀包含我想要保存的漸變樣式,以及我不知道矩形如何轉換爲路徑和顏色數據。如何在XAML/WPF中存儲和檢索多個形狀?

謝謝!

回答

7

您應使用繪圖和使用DrawingBrush像KP阿德里安建議或DrawingImage和Image控件中顯示,但如果你不能使用繪圖你可以使用裏面畫布VisualBrush。

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
<Page.Resources> 
    <VisualBrush x:Key="Icon"> 
     <VisualBrush.Visual> 
      <Canvas Width="10" Height="10"> 
       <Ellipse Width="5" Height="5" Fill="Red"/> 
       <Ellipse Width="5" Height="5" Fill="Blue" Canvas.Left="5" Canvas.Top="5"/> 
      </Canvas> 
     </VisualBrush.Visual> 
    </VisualBrush> 
</Page.Resources> 
    <Rectangle Width="100" Height="100" Fill="{StaticResource Icon}"/> 
</Page> 
3

您不希望使用Canvas將這些資源存儲在資源字典中。幾何圖形的根源大概就像一個DrawingBrush(特別是如果你使用Expression Design中創建的圖像),這些都是需要被添加到資源字典,像這樣的項目:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <DrawingBrush x:Key="YourResourceKey"> 
<DrawingBrush.Drawing> 
<DrawingGroup> 
<!-- This can change a lot, but a typical XAML file exported from a Design image would have the geometry of the image here as a bunch of Paths or GeometryDrawings --> 
</DrawingGroup> 
</DrawingBrush.Drawing> 
</ResourceDictionary> 

我假設你知道如何獲得你的應用程序中引用的這個資源字典。

要使用資源,只需將它們分配給相應的屬性即可。對於形狀類型的圖像,可以將它們分配給類似Rectangle的Fill屬性的東西(還有很多其他方法,但這很簡單)。這裏有一個例子:

<Button> 
    <Grid> 
     <Rectangle Fill="{StaticResource YourResourceKey}" /> 
    </Grid> 
</Button>