【问题标题】:Error while binding image source in DataTemplate在 DataTemplate 中绑定图像源时出错
【发布时间】:2013-01-05 13:50:02
【问题描述】:

我有一个 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 错误:1:无法创建默认转换器以在类型“System.Windows.Controls.Image”和“System.Windows.Media.ImageSource”之间执行“单向”转换。考虑使用 Binding 的 Converter 属性。绑定表达式:路径=图像; DataItem='ImageItemViewModel' (HashCode=7670737);目标元素是'图像'(名称='');目标属性是'Source'(类型'ImageSource')

System.Windows.Data 错误:5:BindingExpression 生成的值对目标属性无效。;值='System.Windows.Controls.Image' BindingExpression:Path=Image; DataItem='ImageItemViewModel' (HashCode=7670737);目标元素是'图像'(名称='');目标属性是'Source'(类型'ImageSource')

当我把它工作:

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

而不是

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

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

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

【问题讨论】:

    标签: c# wpf image binding


    【解决方案1】:

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

    【讨论】:

    • 是的, 就是我要找的!谢谢!
    • 另请参阅this question 关于使用 ContentPresenter 而不是 ContentControl。
    猜你喜欢
    • 1970-01-01
    • 2014-01-06
    • 2013-02-14
    • 2014-05-18
    • 2011-10-06
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    相关资源
    最近更新 更多