2014-11-03 73 views
1

我的問題很簡單,但我找不到可行的解決方案。如何通過windows phone上的代碼設置背景圖片?

我編寫了一個Windows Phone應用程序,我必須更改背景。更改取決於應用程序上的用戶配置文件。如果用戶是男性,則該應用顯示藍色背景,如果她是女性,則爲粉色。

我試圖綁定背景,但我仍然有一個眨眼效果(黑色背景圖像)。 當應用程序在兩個頁面之間導航時非常明顯,但在同一頁面上進行更改時不可見。

我想這些解決方案太多,但在後臺留下黑色:

string uri = String.Format("/Assets/Background{0}.png", App.Context.SelectedUser.IsMan ? "Boy" : "Girl"); 
     var imageBrush = new System.Windows.Media.ImageBrush 
     { 
      ImageSource = new BitmapImage(new Uri(uri, UriKind.Relative)) 
     }; 
     this.Background = imageBrush; 



string uri = String.Format("/Assets/Background{0}.png", App.Context.SelectedUser.IsMan ? "Boy" : "Girl"); 
     var imageBrush = new System.Windows.Media.ImageBrush 
     { 
      ImageSource = new BitmapImage(new Uri(uri, UriKind.Relative)) 
     }; 
     App.RootFrame.Background = imageBrush; 

我試圖以.jpg和.png圖像文件,但沒有工作。

我的代碼錯了嗎? 任何人有一個建議?

非常感謝:-)

回答

2

這個代碼在一個空白的Silverlight應用程序在Windows Phone的8

在XAML:

<Grid x:Name="LayoutRoot" > 
    <Grid.Background> 
     <ImageBrush ImageSource="/Assets/boy.png" Stretch="UniformToFill" /> 
    </Grid.Background> 
    <Button Content="Change" Click="Button_Click" /> 
</Grid> 

,並在後面的代碼:

private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage(); 
     bmp.UriSource = new Uri("/Assets/girl.png", UriKind.Relative); 

     var imageBrush = new System.Windows.Media.ImageBrush 
     { 
      ImageSource = bmp 
     }; 

     LayoutRoot.Background = imageBrush; 
    } 
+0

謝謝亞歷克斯,我的代碼錯了。菜鳥的錯誤: - /。在我的代碼中,我使用了「this」,但它不是好目標。就像你寫的一樣,我必須使用Grid(在我們的例子中是「LayoutRoot」)。 – Pascal 2014-11-04 07:09:39