首先,您不需要使用圖像來填充來自URI的背景。
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush(new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
第二,它是一個更好的方式通過創建具有知名度和源屬性的輔助類來設計它的XAML和操縱它從代碼的可見性和來源。不要忘記將INotifyPropertyChanged接口實現到該類中。
<Grid x:Name="myGrid" DataContext="{Binding}" Visibility="{Binding Path=VisibleProperty}">
<Grid.Background>
<ImageBrush x:Name="myBrush" ImageSource="{Binding Path=SourceProperty}"></ImageBrush>
</Grid.Background>
而在代碼:
private void bg6_Click(object sender, RoutedEventArgs e)
{
myGrid.DataContext=new myImagePresenterClass(new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"), Visibility.Visible)
}
public class myImagePresenterClass:INotifyPropertyChanged
{
private URI sourceProperty
Public URI SourceProperty
{
get
{
return sourceProperty;
}
set
{
sourceProperty=value;
if(PropertyChanged!=null){PropertyChanged(this, new PropertyChangedEventArgs("SourceProperty"));}
}
}
//Don't forget to implement the Visible property the same way as SourceProperty and the class constructor.
}
您的grid1位於頁面上嗎?你確定你的圖片加載正確嗎? – Haspemulator
@Haspemulator我在畫布中添加了我的grid1。