2015-05-04 61 views
-1

我正在嘗試模擬網格庫存系統。我有一些行和列的這個網格。我有一個資源是一個圖像。我得到的錯誤是:WPF從圖像資源分配邊框背景

無法隱式轉換類型「System.Windows.Controls.Image」到「System.Windows.Media.Brush」

如果我改變我的形象轉換爲圖像刷,然後該項目編譯,但EXE崩潰馬上。

<Grid x:Name="MasterGrid" Margin="0"> 
    <Grid.Resources> 
     <Image x:Key="notepad" Source="notepad_16x16.jpg" /> 
    </Grid.Resources> 

// create a border and set it's background image 
Border border = new Border(); 
border.Visibility = System.Windows.Visibility.Visible; 
var img = (Image)MasterGrid.FindResource("notepad"); 
border.Background = img; 

// add the border to the grid 
Grid.SetRow(border, 0); 
Grid.SetColumn(border, 1); 
Grid.SetRowSpan(border, 1); 
Grid.SetColumnSpan(border, 1); 
InvGrid.Children.Add(border); 

回答

1

border.background期待一個畫筆,並且你正在用圖像填充它。你需要從圖像資源

border.Background = new ImageBrush((BitmapImage)FindResource("notepad")); 

您的圖片資源,應定義創建一個圖像刷如下:

<Grid.Resources> 
    <BitmapImage x:Key="notepad" UriSource="images/notepad_16x16.jpg" /> 
</Grid.Resources> 
+0

我需要在代碼中這樣做。這是所有動態的東西。 – user441521

+0

查看更新的答案。 –

+0

工作。我使用的Image和您使用的BitmapImage有什麼區別?另外,我在我的代碼中注意到RowSpan必須是2.如果它是1,邊框根本不會顯示。如果是2,那麼它通常在1個單元中顯示。我想如果RowSpan是2,它會佔用2行,但事實並非如此。爲什麼會這樣? – user441521

0
<Grid.Background> 
     <ImageBrush ImageSource="C:\... your path to the image\notepad_16x16.jpg"/> 
    </Grid.Background> 

這個工作對我來說沒有設置邊界。

+0

這就好比一個網格的庫存,其中每個「細胞」可以有它自己的形象代表一個物品(如健康藥水或類似的東西)。 – user441521