我将imagebrush源绑定到xaml中的datatemplate。 datatemplate是--->
<DataTemplate x:Key="UserGridListTemplate">
<Grid Height="140" Width="155">
<Grid.Background>
<ImageBrush ImageSource="{Binding imagePath}"/>
</Grid.Background>
</Grid>
</DataTemplate>
和xaml ---&gt;
<ListBoxItem ContentTemplate="{StaticResource UserGridListTemplate}" >
<local:MultiLineItem ImagePath="/ShareItMobileApp;component/Images/facebook-avatar(1).png"/>
</ListBoxItem>
但发生了异常 AG_E_PARSER_BAD_PROPERTY_VALUE [行:3位置:33]
任何人都可以帮我这个吗?
答案 0 :(得分:3)
您收到该错误的原因是ImageBrush
不是来自FrameworkElement
,这意味着您无法直接绑定数据。您可以创建一个转换器,将imagePath
转换为ImageBrush,并将ImageBrush设置为网格Background
属性的背景。
首先,您需要创建一个转换器,将路径字符串转换为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的背景绑定上使用该转换器(在您将其添加为具有键ImgPathConverter
的资源之后)。
<DataTemplate x:Key="UserGridListTemplate">
<Grid Height="140" Width="155"
Background={Binding imagePath, Converter={StaticResource ImgPathConverter}}/>
</DataTemplate>