简体   繁体   English

使用datatemplate将字符串列表绑定到列表框

[英]Bind list of string to listbox with datatemplate

Hi I need bind data to listboxx with datateplate in listbox but I get this: System.Colllections.Generic.List´1[System.String] instead of a list of items. 嗨,我需要使用listte中的datateplate将数据绑定到listboxx,但是我得到了: System.Colllections.Generic.List´1 [System.String]而不是项目列表。

<ListBox x:Name="lbMenu" ItemsSource="{Binding MyDataForLunchGrid}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock x:Name="tbMenu" Text="{Binding vydajnaMenus}"/>
                <TextBlock x:Name="tbMenuNumber" Text="{Binding vydajnaNumber}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Data binding: 数据绑定:

_myDataForLunchGrid.Add(new BindingData
{             
    vydajnaMenus = Vydajna1Menus.Select(s => s.ToString()).ToList(),
    vydajnaNumber = "01"
});
OnPropertyChanged("MyDataForLunchGrid");

MyCollection in mainpage 主页中的MyCollection

  private ObservableCollection<BindingData> _myDataForLunchGrid = new ObservableCollection<BindingData>();

    public ObservableCollection<BindingData> MyDataForLunchGrid
    {
        get { return _myDataForLunchGrid; }
        set { _myDataForLunchGrid = value; }
    }

Class BindingData 类BindingData

public List<string> vydajnaMenus { get; set; }
public string vydajnaNumber { get; set; }

Any idea why I get System.Colllections.Generic.List´1[System.String] instead of a list of items.? 知道为什么我得到System.Colllections.Generic.List´1 [System.String]而不是项目列表吗?

I you want to show collection of strings in individual list item, then you need to some how concatenate the strings. 我想在单个列表项中显示字符串集合,然后需要一些如何串联字符串。 Otherwise the runtime will simply call the ToString() on the object. 否则,运行时将仅在对象上调用ToString()。

I think the simplest way is to write a Converter which will concatenate strings in any collection. 我认为最简单的方法是编写一个Converter,它将连接任何集合中的字符串。

OK I get it to work. 好,我知道了。 Its not ideal solution but work great. 它不是理想的解决方案,但是效果很好。

                foreach (var myVar in Vydajna1Menus)
                {  
                _myDataForLunchGrid.Add(new BindingData
                {
                    vydajnaMenus = myVar,
                    vydajnaNumber ="0"+numberOfFood.ToString()
                });
                }
                OnPropertyChanged("MyDataForLunchGrid");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM