1

I have ~30 controls, each with the same model. I want, instead of having ~30 properties bound and ~30 private variables, to bind to an array, allowing me also to loop on the properties

For examle,

Say I have the following (It's just an example)

public class MyImage
{
    public String source { get; set;}
    public String tooltip { get; set;}
}

xaml

<Grid>
    <Image Name="image0" Source="{Binding MyImage0.source"}/>
    <Image Name="image1" Source="{Binding MyImage1.source"}/>
    <Image Name="image2" Source="{Binding MyImage2.source"}/>
    ...
</Grid>

I want instaead of that XAML file, to have the source as something like MyImages[0].source so I could also loop over it and set it in runtime and not have to write MyImage0.source="mysource"

3
  • 3
    consider using ItemsControl with ItemsSource set to collection of MyImage objects Commented Apr 27, 2016 at 12:44
  • But how would I then bind to it? Commented Apr 27, 2016 at 12:53
  • Can't MyImage0, MyImage1, MyImage2 be in a single collection of elements? If they are the same class, than it should not be a problem. Commented Apr 27, 2016 at 12:54

1 Answer 1

5

I would suggest the following:

Having a Collection of Type MyImage like:

public ObservableCollection<MyImage> MyImageCollection { get; set; }

and then go with a DataTemplate and ItemsControl in your View:

<Grid>
    <ItemsControl ItemsSource="{Binding MyImageCollection}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding source}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I'll give it a try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.