You asked "how [to] do something like this properly". The WPF way of doing it would be to have a collection of items implemented as a property on your Window
or ViewModel or whatever, then bind an ItemsControl
to that collection.
For example, if you had a collection of strings:
public ObservableCollection<string> MyItems { get; private set; }
// elsewhere in the same class...
MyItems = new ObservableCollection<string>();
MyItems.Add("first");
MyItems.Add("second");
MyItems.Add("etc");
ObservableCollection<T>
is a good collection class to use for WPF as notification of any changes made to the collection (such as adding or removing items) will be pushed to any observers of the collection (such as WPF's binding system).
To see these items in your View (eg. Window
, UserControl
, etc), you would use a control that can display a list of items (one derived from ItemsControl
) and bind that control to the list property, like so:
<Window ... >
<StackPanel>
<ItemsControl ItemsSource="{Binding MyItems}" />
<TextBlock Text="{Binding MyItems.Count}" />
</StackPanel>
</Window>
ObservableCollection<T>
does implement INotifyPropertyChanged
so the Count
property will always reflect the actual number of items in the list.
You don't have to have a list of strings of course, they could be any kind of object. Similarly, you don't have to use an ItemsControl
but could use something like a ListBox
or ListView
instead (they both derive from that base control class). Furthermore, you might want to look into data templating as this can be used to change the visual appearance of the items in the ItemsControl
.