我有一个带有本地数据库 (SQL CE) 的应用程序,我想将一个列表框绑定到一个表 (Car)。但是,我无法将 WriteableBitmap 保存到本地数据库,因此我决定将图像转换为字节数组,因此我需要动态调用该方法。这是我到目前为止所得到的。
[Table]
class Car
{
[Column (IsPrimaryKey=true, IsDbGenerated=true, CanBeNull=false, AutoSync = AutoSync.OnInsert)]
public int ID { get; set; }
[Column (CanBeNull=false)]
public int MakeID { get; set; }
[Column(CanBeNull = false)]
public int ModelID { get; set; }
[Column(CanBeNull = false)]
public int AccountID { get; set; }
[Column(CanBeNull = false)]
public int Year { get; set; }
[Column]
public string Name { get; set; }
[Column]
public byte[] PicBytes { get; set; }
private EntitySet<Maintenance> maintenance;
[Association(Storage = "maintenance", ThisKey = "ID", OtherKey = "CarID")]
public EntitySet<Maintenance> Maintenance
{
set
{
maintenance = value;
}
get
{
if (maintenance == null)
return new EntitySet<Maintenance>();
return maintenance;
}
}
public WriteableBitmap GetPicture()
{
using (var memoryStream = new MemoryStream(PicBytes))
{
return PictureDecoder.DecodeJpeg(memoryStream);
}
}
}
这是 XAML:
<ListBox Name="carList" Grid.RowSpan="2" Width="480" SelectionChanged="carList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="205"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.RowSpan="4"
Grid.Column="0"
Source="{Binding PicByte}"
Stretch="Uniform"/>
<TextBlock Text="{Binding Name}"
TextWrapping="Wrap"
Grid.Row="0"
Grid.Column="1"
VerticalAlignment="Stretch"
HorizontalAlignment="Center"
Width="160"/>
<TextBlock Text="{Binding MakeID}"
TextWrapping="Wrap"
Grid.Row="1"
Grid.Column="1"
VerticalAlignment="Stretch"
HorizontalAlignment="Center"
Width="160"/>
<TextBlock Text="{Binding ModelID}"
TextWrapping="Wrap"
Grid.Row="2"
Grid.Column="1"
VerticalAlignment="Stretch"
HorizontalAlignment="Center"
Width="160"/>
<TextBlock Text="{Binding Year}"
TextWrapping="Wrap"
Grid.Row="3"
Grid.Column="1"
VerticalAlignment="Stretch"
HorizontalAlignment="Center"
Width="160"/>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的主要问题是图像,如何从 XAML 调用 GetPicture() 方法。还是我应该用 C# 来做这一切?
编辑:我找到了解决问题的方法
try
{
var db = MHDatabase.GetDatabase();
var query = from car in db.Cars
join make in db.Makes on car.MakeID equals make.ID
join model in db.Model on car.ModelID equals model.ID
select new
{
Name = car.Name,
Make = make.Name,
Model = model.Name,
Picture = car.GetPicture(),
Year = car.Year
};
carList.ItemsSource = query;
}
catch (Exception)
{
}