如何使用C#for WP8在网格中显示图像?

时间:2013-01-22 20:51:17

标签: c# xaml windows-phone-8

我需要在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;          
    }

3 个答案:

答案 0 :(得分:3)

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

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;          
}

答案 1 :(得分: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.
}

答案 2 :(得分: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;

    }