我正在将 imagebrush 源绑定(bind)到我在 xaml 中的数据模板。
数据模板是--->
<DataTemplate x:Key="UserGridListTemplate">
<Grid Height="140" Width="155">
<Grid.Background>
<ImageBrush ImageSource="{Binding imagePath}"/>
</Grid.Background>
</Grid>
</DataTemplate>
和xaml--->
<ListBoxItem ContentTemplate="{StaticResource UserGridListTemplate}" >
<local:MultiLineItem ImagePath="/ShareItMobileApp;component/Images/facebook-avatar(1).png"/>
</ListBoxItem>
但发生异常
AG_E_PARSER_BAD_PROPERTY_VALUE [行:3 位置:33]
谁能帮我解决这个问题???
最佳答案
您收到该错误的原因是因为 ImageBrush
并非源自 FrameworkElement
这意味着您不能像那样直接绑定(bind)数据。您可以创建一个转换器来转换您的 imagePath
进入 ImageBrush 并将 ImageBrush 设置为网格 Background
的背景属性(property)。
首先,您需要创建一个转换器来将您的路径字符串转换为 ImageBrush。
public class ImagePathConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter)
{
if(value == null) return null;
Uri uri = new Uri(value.ToString(), UriKind.RelativeOrAbsolute);
ImageBrush ib = new ImageBrush();
ib.ImageSource = new BitmapImage(uri);
return ib;
}
public object ConvertBack(object value, Type targetType, object parameter)
{
throw new NotImplementedException();
}
}
然后,您可以在 Grid 的后台绑定(bind)上使用该转换器(在您将其添加为具有键
ImgPathConverter
的资源之后)。<DataTemplate x:Key="UserGridListTemplate">
<Grid Height="140" Width="155"
Background={Binding imagePath, Converter={StaticResource ImgPathConverter}}/>
</DataTemplate>
关于c# - datatemplate 绑定(bind)图片刷源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15813980/