WPF:如何绑定图像? [英] Wpf: How to bind an image?
本文介绍了WPF:如何绑定图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想滚动从集合中拍摄的图像.我有以下代码:
I want to simply scroll images that taken from a collection. I have this code:
public class RadioStation
{
private int id;
public BitmapImage bitmap;
private Uri link;
public RadioStation(int id, BitmapImage bitmap, Uri link)
{
this.id = id;
this.bitmap = bitmap;
this.link = link;
}
public int getId()
{
return this.id;
}
public Uri getLink()
{
return this.link;
}
public BitmapImage getBitmap()
{
return this.bitmap;
}
}
public class RadioStations : ObservableCollection<RadioStation>
{
public RadioStations() : base()
{
for (int i = 1; i <= 5; i++)
{
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(@"Resources\RadioStations\Images\" + i + ".jpg", UriKind.Relative);
bitmap.EndInit();
Add(new RadioStation(i, bitmap, null));
}
}
}
和
<Window x:Class="DataTemplatingSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataTemplatingSample"
SizeToContent="WidthAndHeight"
Title="Introduction to Data Templating Sample">
<Window.Resources>
<local:RadioStations x:Key="radioStationsList"/>
<ObjectDataProvider ObjectType="{x:Type local:RadioStation}" x:Key="MyClass" />
<ObjectDataProvider ObjectInstance="{StaticResource MyClass}" MethodName="getBitmap" x:Key="MyImage" />
<DataTemplate x:Key="radioStationTemplate">
<Border Name="border" BorderBrush="Aqua" BorderThickness="1" Padding="5" Margin="5">
<Image Source="{Binding Source={StaticResource MyImage}}" Width="60" Height="60" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Border>
</DataTemplate>
</Window.Resources>
<StackPanel Orientation="Horizontal" CanHorizontallyScroll="True" ScrollViewer.VerticalScrollBarVisibility="Disabled" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.CanContentScroll="True">
<ListBox x:Name="list" Width="400" Margin="10"
ItemsSource="{StaticResource radioStationsList}"
ItemTemplate="{StaticResource radioStationTemplate}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel IsItemsHost="True" Orientation="Horizontal" ScrollViewer.CanContentScroll="True"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</StackPanel>
</Window>
由于某种原因,图像不会显示,仅显示边框.我究竟做错了什么?(一个简单的Image控件可用于位图)
From some reason the images won't appear, only the borders. What am I doing wrong? (A simple Image control works with the bitmap)
谢谢!
推荐答案
将BitmapImage设置为属性
Maket BitmapImage as property
public BitmapImage Image
{
get
{
return this.bitmap;
}
}
然后将Binding更改为
And change Binding to
<Image Source="{Binding Image}" .../>
这篇关于WPF:如何绑定图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文