datatemplate绑定图像画笔源

时间:2013-04-04 14:24:27

标签: c# windows-phone-7 xaml datatemplate

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

任何人都可以帮我这个吗?

1 个答案:

答案 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>
相关问题