我想简单地滚动从集合中获取的图像。我有这段代码:
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>
由于某种原因,图像不会出现,只有边框。我究竟做错了什么? (一个简单的图像控件与位图一起使用)
谢谢!
答案 0 :(得分:0)
将Maket BitmapImage作为属性
public BitmapImage Image
{
get
{
return this.bitmap;
}
}
将Binding更改为
<Image Source="{Binding Image}" .../>
答案 1 :(得分:0)
试试这个
RaisePropertyChanged当您更新图像以便UI得到通知时,因此UI了解更改
将其更改为public BitmapImage bitmap
喜欢这个
private BitmapImage _bitmap;
public BitmapImage Bitmap
{
get { return _bitmap; }
set { _bitmap= value;
RaisePropertyChanged("Bitmap");}
}
图像Bindiing的简要示例
XAML
<Grid>
<Image Stretch="UniformToFill" Source="{Binding Photo}" Margin="0,0,10,10" />
</Grid>
视图模型
private Uri _photo;
public Uri Photo
{
get { return _photo; }
set
{
_photo = value;
RaisePropertyChanged("Photo");
}
}