1

我需要在 WP8 中插入图像。我有一堆图像。单击图像后,必须将其设置为网格的背景。所以我创建了一个空的“grid1”和按钮。在按钮单击事件中编写了以下代码,但图像没有显示!

 private void bg6_Click(object sender, RoutedEventArgs e)
    {
        System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
        Image image = new Image();
        image.Source = new System.Windows.Media.Imaging.BitmapImage(
            new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
        myBrush.ImageSource = image.Source;
       // Grid grid1 = new Grid();
        grid1.Background = myBrush;          
    }
4

3 回答 3

3

很难知道您的图像文件是否在正确的位置并设置为正确的构建类型。我建议向Image failed 事件添加一个事件处理程序。

private void bg6_Click(object sender, RoutedEventArgs e)
{
  System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
  Image image = new Image();
  image.ImageFailed += (s, e) => MessageBox.Show("Failed to load: " + e.ErrorException.Message);
  image.Source = new System.Windows.Media.Imaging.BitmapImage(
  new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
  myBrush.ImageSource = image.Source;
  // Grid grid1 = new Grid();
  grid1.Background = myBrush;          
}
于 2013-01-23T01:11:47.407 回答
2

首先,您不需要使用 Image 从 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.
}
于 2013-01-23T10:10:09.047 回答
0

我发现了错误……对不起,伙计们。我没有正确遵循语法。我错过了 Uri 方法中的“@”。表示这一点的正确方法是

 private void bg1_Click(object sender, RoutedEventArgs e)
    {
        System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
        Image image = new Image();
        image.ImageFailed += (s, i) => MessageBox.Show("Failed to load: " + i.ErrorException.Message);
        image.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"/Assets/bg/bg1.jpg/", UriKind.RelativeOrAbsolute));
        myBrush.ImageSource = image.Source;
        grid1.Background = myBrush;

    }
于 2013-02-01T05:37:28.570 回答