datatemplate绑定图像画笔源

问题描述:

我将imagebrush源绑定到我在xaml中的datatemplate。 所述的DataTemplate是--->datatemplate绑定图像画笔源

<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派生,这意味着你不能直接绑定数据。您可以创建一个转换器,将您的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(); 
    } 
} 

然后,您可以使用您的网格的背景下,结合变频器(你用钥匙ImgPathConverter增加一条,作为一个资源之后)。

<DataTemplate x:Key="UserGridListTemplate"> 
    <Grid Height="140" Width="155" 
    Background={Binding imagePath, Converter={StaticResource ImgPathConverter}}/> 
</DataTemplate> 
+0

thanx @keyboardP ... – 2013-04-04 15:39:18

+0

不客气:) – keyboardP 2013-04-04 15:59:43