如何使用 C# for WP8 在网格中显示图像
本文关键字:显示 显示图 图像 网格 何使用 for WP8 | 更新日期: 2023-09-27 17:55:22
我需要在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;
}
很难知道您的映像文件是否位于正确的位置并设置为正确的构建类型。我建议将事件处理程序添加到图像失败事件中。
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;
}
首先,您不需要使用 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.
}
我发现了错误...对不起,伙计们。我没有正确遵循语法。我错过了 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;
}