I want to show multiple image on a canvas. I need to position them differently in the canvas. I made a class for my images :
class MapItem:Image
{
public int DistanceToTop { get; set; }
public int DistanceToLeft { get; set; }
}
My XAML looks like this :
<UserControl.DataContext>
<Map:MapViewModel/>
</UserControl.DataContext>
<ItemsControl ItemsSource="{Binding All}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="Image">
<Setter Property="Canvas.Left" Value="{Binding DistanceToLeft}" />
<Setter Property="Canvas.Top" Value="{Binding DistanceToTop}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
My ViewModel used as DataContext :
class MapViewModel : ViewModelBase
{
public ObservableCollection<MapItem> All { get; set; }
public MapViewModel()
{
All = new ObservableCollection<MapItem>();
var wSource = new BitmapImage(new Uri(@"ImagePath"));
var wImage = new MapItem { Source = wSource, DistanceToLeft = 20, DistanceToTop = 20 };
test = wImage;
All.Add(wImage);
}
}
Why in the XAML my binding to DistanceToLeft and DistanceToTop are not working ?!?
Isn't it suppose to automatically look in the object use in my ObservableCollection ?
EDIT : I still have my problem. But now I know it's related with the Binding. I'm trying to implement all this using the MVVM pattern using the GalaSoft framework. So to start I set my DataContext to my MapViewModel. Why can't I acces the properties of the MapItem from my ObservableCollection ?
EDIT : Finally with the help of Clemens and Rachel I ended up with this.
My MapItem Class:
class MapItem:Image
{
public LatLon CoordMiddleOfImage { get; set; }
public LatLon CoordTopLeftOfImage { get; set; }
public int DistanceToTop
{
get { return (int) Canvas.GetTop(this); }
set { Canvas.SetTop(this, value); }
}
public int DistanceToLeft
{
get { return (int)Canvas.GetLeft(this); }
set { Canvas.SetLeft(this, value); }
}
public int ZOrder
{
get { return Panel.GetZIndex(this); }
set { Panel.SetZIndex(this, value); }
}
}
And my XAML like this :
<ItemsControl ItemsSource="{Binding All}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas ClipToBounds="True" SnapsToDevicePixels="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
It works like a charm for now :-)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…