gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:35:49 27 4
gpt4 key购买 nike

我有一个带有 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com