wpf DataGrid列中绑定图片删除

wpf界面

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MainWindw.CommHelper">

 <DataGridTemplateColumn Header="图片" MinWidth="150">
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <Image Height="100" Width="100"  Source="{Binding Path=FilePath, Converter={StaticResource ImagePathConverter}}" />
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>

 <Window.Resources>
        <local:ConvertTextToImage  x:Key="ImagePathConverter"   />
    </Window.Resources>

c#代码

public   class ConvertTextToImage : IValueConverter
{
       #region IValueConverter Members
       public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       {
           if (value == null)
               return null;
 
           if (!string.IsNullOrEmpty(value.ToString()))
           {
               BitmapImage bi = new BitmapImage();
               bi.BeginInit();
               bi.UriSource = new Uri(value.ToString(), UriKind.RelativeOrAbsolute);
               bi.CacheOption = BitmapCacheOption.OnLoad;
               bi.EndInit();
               return bi;
}
 
           return null;
       }
       public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       {
           throw new NotImplementedException();
       }
       #endregion
}
 

在按钮中删除绑定的图片时候 不会报错

该图片不能删除,因为别的进程正在使用它

如果程序报错

WPF, binding to an image without file access exceptions(绑定的图像文件访问异常)

可能是该文件不是图像格式文件造成。文件格式必须是png,jpg之类的图像格式才行。

原文地址:https://www.cnblogs.com/z_lb/p/2980987.html