2009-11-12 140 views
16

我正在學習WPF,我似乎無法找到一種方法來完成這項工作。如何將.PNG圖像設置爲我的WPF窗體的TILED背景圖像?

這裏是我的代碼:

<Window x:Class="Test.MainWindow" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="Test" Height="600" Width="800" > 
<DockPanel> 
    <Menu DockPanel.Dock="Right" 
      Height="30"    
      VerticalAlignment="Top" 
      Background="#2E404B" 
      BorderThickness="2.6"> 
     <Menu.BitmapEffect> 
      <DropShadowBitmapEffect Direction="270" ShadowDepth="3" Color="#2B3841"/> 
     </Menu.BitmapEffect>       
    </Menu> 
</DockPanel> 

我怎樣才能讓一個平鋪的背景圖像出現在哪裏?

回答

24

改變菜單項或者,也許整個窗口,你可以使用Visual Brush

<Window 
    x:Class="Test.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Test" Height="600" Width="800"> 
    <Window.Background> 
    <VisualBrush TileMode="Tile" Viewport="0,0,0.5,0.5"> 
     <VisualBrush.Visual> 
     <Image Source="image.png"></Image> 
     </VisualBrush.Visual> 
    </VisualBrush> 
    </Window.Background> 
</Window> 
+0

請您解釋一下ViewPort中的四位數字是什麼意思?我已經和他們一起玩過了,但我似乎無法弄清楚他們做得簡潔。 – 2009-11-12 23:12:00

+5

視口屬性設置基本圖塊的位置和尺寸。看看這裏的例子:http://msdn.microsoft.com/en-us/library/system.windows.media.tilebrush.viewport.aspx 基本上,「0,0,0.5,0.5」意味着基地磚將從點(0,0)到(0.5,0.5)佔用空間 - 即從輸出區域的左上角到中心。 (1,1)是右下角。 您應該使用MSDN Library。這非常有用。所有的答案都在那裏。 – jfrej 2009-11-12 23:31:32

1

若要設置背景圖片來控制你必須添加圖像刷標記

<MenuItem.Background> 
    <ImageBrush ImageSource="path/to/image.png" /> 
</MenuItem.Background> 

如果你想使一個背景,你必須通過窗口

44

設置ViewportUnits絕對,這將允許你定義在視窗中的圖像的像素大小。在我的例子中,圖像大小是32x32。

<Window.Background> 
    <ImageBrush ImageSource="image.png" TileMode="Tile" ViewportUnits="Absolute" Viewport="0,0,32,32"/> 
</Window.Background> 
+4

這是更好的答案 – 2012-04-12 10:00:49

+0

接受的答案不適合我;這一個。 – RandomEngy 2012-11-20 05:18:38

+1

哦,男人,我拉着我的頭髮試圖找出爲什麼這不適合我。原來我使用'ViewboxUnits'而不是'ViewportUnits':S – craftworkgames 2016-10-05 11:36:50