在DataGrid-Column中显示图像
本文关键字:显示图 图像 显示 DataGrid-Column | 更新日期: 2023-09-27 18:05:58
我试图在DataGrid-Column中显示其他数据旁边的图像。我的模型是这样的:
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public Bitmap Image { get; set; }
}
ViewModel:
public ObservableCollection<Person> Persons
{
get
{
return this.persons;
}
set
{
this.persons = value;
}
}
我的DataGrid是这样的:
<DataGrid Name="Persons"
Grid.Row="1"
Grid.Column="0"
Margin="10"
AutoGenerateColumns="False"
IsReadOnly="True"
ItemsSource="{Binding Path=Persons}">
<DataGrid.Columns>
<DataGridTemplateColumn Width="80">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Width="120"
Binding="{Binding Path=Name}"
Header="Name" />
<DataGridTextColumn Width="120"
Binding="{Binding Path=Address}"
Header="Address" />
</DataGrid.Columns>
</DataGrid>
名称和地址显示正确,但图像是空的…你知道我做错了什么吗?
提前谢谢你,祝你有美好的一天
如果您的Image
是System.Drawing.Bitmap
的,您应该将其更改为System.Windows.Media.Imaging.BitmapImage
,然后更改Image.Source
绑定,目前将整个Person
对象绑定到其Image
属性
<Image Source="{Binding Image}" />
尝试使用该代码来显示您的图像:
<DataGridTemplateColumn Width="80">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Image}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
在项目中添加图像文件夹,并在同一文件夹中添加图像。使用以下代码访问
<Columns>
<ItemTemplate >
<asp:ImageButton ID="ImageButton1" runat ="server" CommandName="Preview" ImageUrl="~/images/MSWord_Icon.jpg"/>
</ItemTemplate>
</Columns>
您需要为图像设置一些高度和宽度,如
<Image Source="{Binding}" Height="200" Width="200"/>
xmlns:converter="clr-namespace:ProjectName.Converters"
<Window.Resource>
<converter:BindableConverter x:Key="bindableConverter"/>
</Window.Resource>
<DataGridTemplateColumn Header="HeaderName">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image x:Name="BindImg" Height="35" Width="35" Source="{Binding IsBindable,Converter={StaticResource bindableConverter}}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
public class BindableConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string imageSource = string.Empty;
bool isBinded;
if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
{
imageSource = "../../Resource/Images/unbinded.jpg";
}
if (Boolean.TryParse(value.ToString(), out isBinded))
{
if (isBinded)
{
imageSource = "../../Resource/Images/binded.jpg";
}
else
{
imageSource = "../../Resource/Images/unbinded.jpg";
}
}
return imageSource;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}