Search code examples
c#.netwpf

How to access Items from ListBox? - WPF


My problem is that I can't access the properties of the UserСontrol created in the ListBox.

I have an empty ListBox to which I add a UserСontrol by clicking a button.

private void addButtton_Click(object sender, RoutedEventArgs e)
{
    SignalButton signalButton = new SignalButton(); // Initialization UserControl
    signalButton.Width = 200;
    signalButton.Height = 45;
    mainListBox.Items.Insert(0, signalButton);
} 

How do I access the UserСontrol properties located in the ListBox?


Solution

  • In order to access to the added UserControl, you need to keep track of them in a List<UserControl> _useControlList; outside the ListBox, and access to one, for instance, the last one by _useControlList.Last(), and then access to its properties.

    But then you are not separating design and its logic, which can be a problem (maintenance, testability, flexibility, understandability etc).

    I have a feeling that you are not separating design and logic (like in MVVM), which will make your project super messy and hard to maintain and understand. For that I recommend that you define a UserControl as a View, with its design defined in the XAML, and associate a ViewModel, where you put the View logic. Then your ListBox/ListView will use a DataTemplate.

    Example:

    View (extract):

    <ListView Background="Transparent" IsSynchronizedWithCurrentItem="True"
              ItemsSource="{Binding MidiCLPCollection}"
              SelectedItem="{Binding SelectedMidiCLPVM}">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel IsItemsHost="True" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.ItemTemplate>
            <DataTemplate DataType="{x:Type local:MidiCLPViewModel}">
                <local:MidiCLPView/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    

    ViewModel (extract):

    public ObservableCollection<MidiCLPViewModel> MidiCLPCollection
        { get; protected set; } = new();
    

    and MidiCLPView is your UserControl (.xaml + .xaml.cs).