c# - datatemplate绑定(bind)图片画笔源码

标签 c# windows-phone-7 xaml datatemplate

我正在将 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 属性的背景。

首先,您需要创建一个转换器来将路径字符串转换为 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();
    }
}

然后,您可以在网格的后台绑定(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/

相关文章:

c# - ASP .Net MVC 因未经授权的请求而获得装饰角色

windows-phone-7 - 如何在 WP7 应用程序磁贴中隐藏应用程序标题

c# - 如何使用按钮创建自定义控件以及如何在 silverlight for windows mobile 7 中添加事件按钮单击事件

c# - WP7如何让网格尺寸适配图像尺寸

WPF菜单-不必要的边框

wpf - WPF 中的样式覆盖

c# - 由于某种原因,字节乘以字节是 int。为什么?无法将类型 'int' 隐式转换为 'byte' 。存在显式转换

c# - 在 wpf 中绑定(bind)值为空或为空时如何使用触发器/(等)标记内容集

c# - asp.net中自动调用文本框textchanged事件

c# - 重命名主窗口的最佳方法