2016-11-17 25 views
0

嘿,我有以下代碼假設採取我的JPG圖像,並將其放置在窗體的背景。但是,我看到的只是一個黑色背景。WPF在窗體上加載背景圖像

Dim myBrush As New ImageBrush() 
Dim image As New Image() 
Dim grid As New Grid() 

image.Source = New BitmapImage(New Uri("pack://application:,,,/WpfApplication1;component/Resources/1680-logoless.jpg")) 
myBrush.ImageSource = image.Source 
grid.Background = myBrush 

enter image description here

這是我目前的XAML:

<Window x:Class="MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:WpfApplication1" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" Margin="157,145,0,0"/> 
     <Label x:Name="label1" Content="Label" HorizontalAlignment="Left" Margin="68,59,0,0" VerticalAlignment="Top" Width="111"/> 
     <Button x:Name="button" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="335,62,0,0"/> 
     <Button x:Name="button1" Content="Encrypt" HorizontalAlignment="Left" Height="17" Margin="335,123,0,0" VerticalAlignment="Top" Width="120"/> 
     <TextBox x:Name="toEncrypt" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="172" Margin="335,145,0,0"/> 
     <TextBox x:Name="toDecrypt" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="172" Margin="335,173,0,0"/> 
     <Button x:Name="button2" Content="Decrypt" HorizontalAlignment="Left" Height="23" Margin="335,201,0,0" VerticalAlignment="Top" Width="120"/> 

    </Grid> 
</Window> 

任何人都看不到任何東西我可能會錯過?

+0

您是否將圖像文件的Build Action設置爲'Resource'? – Clemens

+0

@Clemens是的,是的,我做到了。 – StealthRT

+0

什麼是圖像控制?只需編寫'myBrush.ImageSource = New BitmapImage(...)'。 – Clemens

回答

1

設置x:Name屬性在XAML的電網,這將在主窗口類中創建一個字段:

<Window ...> 
    <Grid x:Name="rootGrid"> 
     ... 
    </Grid> 
</Window> 

然後,而不是創建一個新的網格實例,設置一個在XAML中聲明的背景:

rootGrid.Background = New ImageBrush(New BitmapImage(
    New Uri("pack://application:,,,/Resources/1680-logoless.jpg"))) 
+0

它是!感謝您的幫助,Clemens – StealthRT