我正在将 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/