问题描述
我在 WPF 中有一个矩形,我可以使用 <ImageBrush ImageSource="Images\10564.jpg"/>
设置它的填充.这是我的矩形 XAML:
I have a Rectangle in WPF, I can set it's Fill by using <ImageBrush ImageSource="Images\10564.jpg"/>
. This is my XAML for Rectangle:
<Rectangle.Fill>
<ImageBrush ImageSource="Images\10564.jpg"/>
</Rectangle.Fill>
我希望能够使用绑定从代码动态更改填充.图像名称存储在我的数据库中,所有文件(图像)的文件路径和扩展名都相同.
I want to be able to change Fill dynamically from code using bindings.Image names are stored in my database and file path and extensions are the same for all files (images).
这是我试过的:
<ImageBrush ImageSource="{Binding Path=itemNumber, StringFormat='Images\{0}\.jpg'}"/>
但是使用上面的这段代码我得到了异常/错误:'System.Windows.Baml2006.TypeConverterMarkupExtension' throw an exception.'行号480"和行位置34".
我想这与将字符串转换为路径有关吗?
But using this code above i get exception/error: 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '480' and line position '34'.
I guess it has something to do with converting string to path?
使用转换器一切正常!这是有效的 VB.NET 类:
Using converter everything works!Here is VB.NET class which works:
Imports System.Globalization
Public Class ImageSourceConverter
Implements IValueConverter
Private Function IValueConverter_Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
Return New BitmapImage(New Uri(String.Format("pack://application:,,,/Images/{0}.jpg", value)))
End Function
Private Function IValueConverter_ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
Throw New NotSupportedException()
End Function
结束课程
推荐答案
您应该使用绑定转换器,它可能如下所示:
You should use a Binding Converter, which may look like this:
public class ImageSourceConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return new BitmapImage(new Uri(
string.Format("pack://application:,,,/Images/{0}.jpg", value)));
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
将转换器声明为 XAML 资源,如下所示:
Declare the converter as XAML resource like this:
<Window.Resources>
<local:ImageSourceConverter x:Key="ImageSourceConverter" />
</Window.Resources>
并在您的绑定中使用它:
und use it in your Binding:
<ImageBrush ImageSource="{Binding Path=itemNumber,
Converter={StaticResource ImageSourceConverter}}"/>
可以在此处找到有关使用转换器的更多信息:https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-convert-bound-data
More about using converters can be found here: https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-convert-bound-data
这篇关于ImageSource 使用 WPF 中数据库中的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!