在DataTemplate中绑定图片源时出现错误。

3

我有一个带有画布的ItemsControl,应该在其中展示我的图片。我有一个ObservableCollection,里面是一个包含属性的类的对象:

Image Image;
double X;
double Y;

我的 XAML 包含以下代码:

<ItemsControl ItemsSource="{Binding Images}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas AllowDrop="True" Drop="Canvas_Drop_1" MouseDown="canvas_MouseDown_1" Background="{StaticResource LightColor}" Name="canvas" >
            </Canvas>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding Image}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="Canvas.Top" Value="{Binding Y}" />
            <Setter Property="Canvas.Left" Value="{Binding X}" />
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

这里的Images是我的ObservableCollection。现在遇到的问题是我无法将该集合中的Image绑定到DataTemplate中的ImageSource上。如果我按照之前写的那样做,就会出现如下错误:

System.Windows.Data Error: 1 : 无法创建默认转换器以在类型“System.Windows.Controls.Image”和“System.Windows.Media.ImageSource”之间进行单向转换。请考虑使用Binding的Converter属性。 BindingExpression:Path = Image; DataItem ='ImageItemViewModel' (HashCode = 7670737);目标元素是'Image'(名称=''); 目标属性是“Source”(类型为“ImageSource”)

System.Windows.Data Error: 5 : BindingExpression生成的值对于目标属性无效; Value ='System.Windows.Controls.Image' BindingExpression:Path = Image; DataItem ='ImageItemViewModel' (HashCode = 7670737); 目标元素是'Image'(名称=''); 目标属性是“Source”(类型为“ImageSource”)

但是,如果我使用以下代码,则可以解决这个问题:

<Image Source="{Binding Image.Source}"/>

替代

<Image Source="{Binding Image}"/>

但这样做我就失去了该图像的所有属性(如效果等)。

所以问题是:我怎样才能将我在集合对象中拥有的整个Image对象放在那里,而不仅仅绑定它的源?

1个回答

4

你的Image属性不应该是一个Image控件,而应该是一个ImageSource,或者可能是Uristring

public class DataItem
{
    public ImageSource Image { get; set; }
    ...
}

或者

public class DataItem
{
    public string ImageUrl { get; set; }
    ...
}

然而,如果你真的需要将属性作为控件,你可以将其放入ContentControl中:
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <ContentControl Content="{Binding Image}"/>
    </DataTemplate>
</ItemsControl.ItemTemplate>

是的,<ContentControl Content="{Binding Image}"/> 这就是我要找的!谢谢! - krajol
请参考这个问题,了解使用ContentPresenter而不是ContentControl的相关信息。 - Clemens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接