Multiple Image in Canvas ItemsControl

纵然是瞬间 提交于 2019-11-27 16:24:40

I don't quite understand why after all you invented the DistanceToLeft and DistanceToTop properties and then struggle with binding. If you want to use Image controls as items, why not directly apply the attached properties Canvas.Left and Canvas.Top:

All = new ObservableCollection<Image>(); // no need for derived MapItem
var wSource = new BitmapImage(new Uri(@"ImagePath")); 
var wImage = new Image { Source = wSource }; 
Canvas.SetLeft(wImage, 20);
Canvas.SetTop(wImage, 20);
All.Add(wImage); 

Hence, no need for a Style:

<ItemsControl ItemsSource="{Binding All}">    
    <ItemsControl.ItemsPanel>    
        <ItemsPanelTemplate>    
            <Canvas />    
        </ItemsPanelTemplate>    
    </ItemsControl.ItemsPanel>    
</ItemsControl> 

However, you should consider to create a real ViewModel class that is not a control, something like this:

public class ImageItem
{
    public string Source { get; set; }
    public double Left { get; set; }
    public double Top { get; set; }
}

Use it similar to your MapItem class

All = new ObservableCollection<ImageItem>();
ImageItem image = new ImageItem { Source = @"ImagePath", Left = 20, Top = 20 };
All.Add(image);

You would now define an ItemContainerStyle like this:

<ItemsControl.ItemContainerStyle>
    <!-- ContentPresenter is the default item container in ItemsControl -->
    <Style TargetType="ContentPresenter">
        <Setter Property="Canvas.Left" Value="{Binding Left}"/>
        <Setter Property="Canvas.Top" Value="{Binding Top}"/>
        <Setter Property="ContentTemplate">                        
            <Setter.Value>
                <DataTemplate>
                    <Image Source="{Binding Source}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ItemsControl.ItemContainerStyle>

An ItemsControl wraps each item in a ContentPresenter, so the style in ItemContainerStyle is for the ContentPresenter, not the Image

If you remove TargetType="Image" from your style it should work fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!