2013-04-04 46 views
2

我將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]

任何人都可以幫我解決這個問題?

回答

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(); 
    } 
} 

然後,您可以使用您的網格的背景下,結合變頻器(你用鑰匙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