2011-10-07 30 views
2

我想知道如何在代碼中而不是在xaml中動態地將圖片添加到按鈕。有人曾建議繼續通過以下方式如何在Silverlight中的WP7應用程序的代碼隱藏文件中設置背景圖片

ImageBrush brush = new ImageBrush(); 
brush.ImageSource = new BitmapImage(new Uri(@"Images/myImage.png", UriKind.Relative)); 
AlphabetButton.Background = brush; 

,但不是由智能感知,雖然我能找到BitConvertor和Bitmapcache檢測BitmapImage的。 如果不是這種方法,怎麼回事,我會設置背景圖片

回答

8

代碼:

ImageBrush background = new ImageBrush(); 
background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"SplashScreenImage.jpg", UriKind.Relative)); 
Button1.Background = background; 

按預期工作。 BitmapImage在System.Windows.dll中,它應該已經存在於你的WP7項目中。

+0

謝謝.. :)我添加using.windows.media.imaging到命名空間。現在可以訪問BitmapImage。 – alfah

1

我發現只需將Image控件放在要顯示的按鈕後面並使透明背景保持不變即可輕鬆簡單。

這消除了爲按鈕創建單獨的畫刷的需要,並且如果要在圖像上添加測試,還可以使其更具可擴展性。恕我直言

+0

謝謝。我對WP和Silverlight以及C#都很陌生。所以你可以在圖像控制方面多給點幫助。是的,我每次都創建單獨的畫筆,這確實很奇怪。 – alfah

相關問題