[英]How to insert image near text in wpf DataGrid c#
我編寫了填充DataGrid的代碼。 一切正常,但現在我想在“名稱”字段附近添加圖片。 該圖像的鏈接由數據庫獲取。 該圖像為svg格式,為此,我正在使用資源svg2xaml。
這行代碼返回圖像:
DrawingImage logo = SvgReader.Load(new MemoryStream(new System.Net.WebClient().DownloadData("http://upload.wikimedia.org/wikipedia/commons/c/c5/Logo_FC_Bayern_München.svg")));
我使用以下代碼填充DataGrid:
MainWindow.AppWindow.Squadre_DataGrid.Items.Add(new Teams.Club_Information
{
name = reader["name"].ToString()
}
這是我的xaml結構:
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path = 'name'}" ClipboardContentBinding="{x:Null}" Header="Codice" Width="*" />
...
有人可以解釋我如何通過代碼添加此圖片嗎?
更新-動態鏈接:
DrawingImage logo = SvgReader.Load(new MemoryStream(new System.Net.WebClient().DownloadData(reader["link"].ToString())));
閱讀器包含鏈接。 我想像參考一樣將此鏈接發送到NameToImageConverter: NameToImageConverter nm = new NameToImageConveter();
但這是不可能的,因為它是一個控件。 那么我該怎么做呢?
如果不想添加新列,則必須用DataGridTemplateColumn替換DataGridTextColumn:
<DataGridTemplateColumn Header="Codice" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding name}" />
<Image Source="{Binding Path=crestUrl, Converter={StaticResource NameToImageConverter}}" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
請注意,您必須將轉換器添加到窗口資源中:
<local:NameToImageConverter x:Key ="NameToImageConverter" />
其中“本地”是轉換器的名稱空間。 和轉換器本身:
public class NameToImageConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// here you can return DrawingImage based on value that represents name field of your structure
// just for example the piece of your code:
if (value is string && !String.IsNullOrEmpty(value as string))
{
return SvgReader.Load(new MemoryStream(new System.Net.WebClient().DownloadData(value as string)));
}
else
{
// if value is null or not of string type
return yourDefaultImage;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.