c# - 在 DataTemplate 中绑定(bind)图像源时出错

标签 c# wpf image binding

我有一个带有 Canvas 的 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 绑定(bind)到 DataTemplate 中的 ImageSource。如果我按照我写的那样去做,我会收到一个错误:

System.Windows.Data Error: 1 : Cannot create default converter to perform 'one-way' conversions between types 'System.Windows.Controls.Image' and 'System.Windows.Media.ImageSource'. Consider using Converter property of Binding. BindingExpression:Path=Image; DataItem='ImageItemViewModel' (HashCode=7670737); target element is 'Image' (Name=''); target property is 'Source' (type 'ImageSource')

System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='System.Windows.Controls.Image' BindingExpression:Path=Image; DataItem='ImageItemViewModel' (HashCode=7670737); target element is 'Image' (Name=''); target property is 'Source' (type 'ImageSource')

当我输入时它起作用了:

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

代替

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

但随后我失去了它所具有的所有图像属性(如效果等)。

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

最佳答案

您的 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>

关于c# - 在 DataTemplate 中绑定(bind)图像源时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14456744/

相关文章:

c# - 从soapxml获取XML子节点值

c# - XAML 中可重用、可重新着色的图标使用什么结构?

c# - DataGrid 列宽不会自动更新

c# - 使用 linq 的 WPF 组合框绑定(bind)

javascript - 在可拖动中预览上传的图像

python - Flask:通过post获取图像

c# - 在 WP7 中反序列化 JSON

c# - 如何将流从 HttpContent 结果上传到 Azure 文件存储

image - Matlab DICOM 切片

c# - 格式化DateTime.Now