K
K
kykyryky2016-10-06 16:14:01
.NET
kykyryky, 2016-10-06 16:14:01

Why does the List binding on the ListBox not work to the end?

There is such code in the ViewModel:

private List<string> items;
public List<string> Items
        {
            get
            {
                items = new List<string> { "1", "2", "3" };
                return items;
            }
        }

XAML:
<ListBox x:Name="listBox"
                 Width="612"
                 Height="475"
                 Margin="24,179,0,0"
                 HorizontalAlignment="Left"
                 VerticalAlignment="Top"
                 ItemsSource="{Binding Path=Items,
                                       Mode=OneWay}">

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

In this case, 3 lines with 1 2 and 3 are displayed in the listbox. Everything seems to be fine.
Then I remove the line with the creation of the list from the getter
private List<string> items;
public List<string> Items
        {
            get
            {
                return items;
            }
        }

and trying to add an element. For example in the ViewModel constructor:
items = new List<string>();
items.Add("4");

However, nothing appears in the listbox. Items.Add("4") - the same nonsense.
What do I need to do so that the element is added and the list is displayed in the listbox?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2016-10-06
@kykyryky

Use ObservableCollection. List does not announce the addition of an element to the list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question