1

Есть следующий класс

public class OneDay
{
    public int Nomber { get; set; }        
    public List<int> Arr = new List<int>();
}

Далее создаю list с его экземплярами, заполняю и привязываю к ListBox

public List<OneDay> Days = new List<OneDay>();
public MainWindow()
{
    InitializeComponent();
    for (int i = 0; i < 365; i++)
    {
        Days.Add(new OneDay());
        Days[Days.Count - 1].Nomber = i + 1;
        for(int j = 0; j<4; j++)
        {
            Days[Days.Count - 1].Arr.Add(10+j);
        }
    listOfDays.ItemsSource = Days;
}

В xaml:

<ListBox x:Name="listOfDays" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>                                    
    <ListBox.ItemTemplate >
        <DataTemplate>
            <StackPanel Orientation="Vertical" Background="Transparent" >
                <Label Background="Red" Content="{Binding Nomber}"></Label>
                <Label Background="Blue" Content="{Binding Arr[0]}"></Label>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>     
</ListBox>

В ListBox в красных Label отображается номер каждого дня из листа Days, а синих label Arr[0] не выводится. В чем ошибка? И как тогда получить элемент коллекции через Binding?

1 ответ 1

3

Привязка в XAML работает только для свойств. В приведённом примере List является не свойством, а полем:

public class OneDay
{
    public int Nomber { get; set; }        
    public List<int> Arr = new List<int>();
}

Попробуйте заменить на

public List<int> Arr { get; set; }

и инициализировать в конструкторе.
Также в новом C# есть inlnie-инициализация для свойств:

public List<int> Arr { get; set; } = new List<int>();
0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.