I’m trying to create a user control that will display a collection of images. I have the user control created with a dependency property for the collection of images. I can databind to that property and display the images fine.
However, I have hard-coded in the size of the collection and I want it to take in an arbitrary number of images and display them.
I am not sure how to dynamically create the images based on the collection of images. I’m sure there is some event that I want to respond to and create my images based on the contents of the dependency property.
public sealed partial class ImageView : UserControl
{
public ImageView()
{
this.InitializeComponent();
scrollViewer.ZoomSnapPoints.Clear();
scrollViewer.ZoomSnapPoints.Add(0.2f);
scrollViewer.ZoomSnapPoints.Add(0.6f);
scrollViewer.ZoomSnapPoints.Add(1.0f);
scrollViewer.ZoomSnapPoints.Add(1.4f);
scrollViewer.ZoomToFactor(0.4f);
}
public static readonly DependencyProperty ImagesProperty = DependencyProperty.Register("Images",
typeof(List<VMImage>), typeof(ImageView), new PropertyMetadata(new List<VMImage>(12)));
public List<VMImage> Images
{
get { return (List<VMImage>)GetValue(ImagesProperty); }
set { SetValue(ImagesProperty, value); }
}
}
<ScrollViewer Height="700" Width="700"
x:Name="scrollViewer"
MinZoomFactor="0.2"
MaxZoomFactor="5.0"
ZoomSnapPointsType="Mandatory">
<Canvas Background="Black" Width="2000" Height="2000" >
<Image Canvas.Left="{Binding Images[0].Location.X}"
Canvas.Top="{Binding Images[0].Location.Y}"
Source="{Binding Images[0].Source}" ></Image>
<Image Canvas.Left="{Binding Images[1].Location.X}"
Canvas.Top="{Binding Images[1].Location.Y}"
Source="{Binding Images[1].Source}" ></Image>
</Canvas>
</ScrollViewer>
You should make your dependency property an
ObservableCollection<VMImage>. This way you can attach a handler to itsCollectionChangedevent and get notified of changes. Just make sure in the property changed callback of your dependency property that you add the event handler to the new value and remove it from the old value.