如何使用 C# for WP8 在网格中显示图像? [英] how to display image in a grid using C# for WP8?

查看:21
本文介绍了如何使用 C# for WP8 在网格中显示图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i need to insert an image in a WP8. i have a stack of images. once i click the image, it has to be set as background for a grid. so i created an empty "grid1" and button. wrote the below code in the button click event, but the image doesnot get displayed !

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

推荐答案

首先,您不需要使用 Image 从 URI 填充背景.

First, you don't need to use Image to fill the background from 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 接口.

Second, it is a WAY better to design it in XAML and manipulate it visibility and source from code by creating the helper class with visibility and source property. Don't forget to implement INotifyPropertyChanged interface into that class.

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

这篇关于如何使用 C# for WP8 在网格中显示图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆