从IList转换为List <t> </t>

时间:2015-02-25 17:00:24

标签: c# wpf list

我知道这个问题已经得到解答,但我已经尝试了很多解决方案,但没有一个能够解决问题。

我有一个图表,在选择一个系列后绑定到IList的对象,但是我无法从IList转换为List;我的演员表中的列表最终为空:

public class ChartData
{
    public string Type { get; set; }
    public int Year { get; set; }
    public int Value { get; set; } 
}

public IList BindSelectedItems
{
    get 
    { 
        return _bindSelectedItems; 
    }
    set
    {
        _bindSelectedItems = value;

        //Solutions I found that don't work:
        IList<ChartData> myList = value.OfType<ChartData>().ToList();
        //IList<ChartData> myList = value.Cast<ChartData>().ToList();

        List<ChartData> cd = myList as List<ChartData>;

        foreach (var c in cd) //does not work b/c myList is empty
        {
            Debug.Print("type is " + c.Type + " cost is " + c.Value + " year is " + c.Year);
        }

        RaisePropertyChanged("BindSelectedItems");
    }
}

IList _bindSelectedItems;

2 个答案:

答案 0 :(得分:0)

问题在绑定目标的签名范围内。您绑定到IList,是否要为要绑定的集合公开持有者/包装器?我相信你想要实际绑定到数据而而不是它的包装

绑定到IList<ChartData>,以便绑定操作可以反射ChartData对象,这是最终目标..


public IList<ChartData> BindSelectedItems
{
    get 
    { 
        return _bindSelectedItems; 
    }
    set
    {
        _bindSelectedItems = value;

        RaisePropertyChanged("BindSelectedItems");
    }
}

IList<ChartData> _bindSelectedItems;

答案 1 :(得分:0)

我意识到我无法实现我对IList的绑定,并且必须使用和ObservableCollection如下:

    ObservableCollection<object> _bindSelectedItems;
    public ObservableCollection<object> BindSelectedItems
    {
        get { return _bindSelectedItems; }
        set
        {

            _bindSelectedItems = value;
            _bindSelectedItems.CollectionChanged += _bindSelectedItems_CollectionChanged;
            RaisePropertyChanged("BindSelectedItems");
        }
    }

    void _bindSelectedItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        ObservableCollection<object> items = sender as ObservableCollection<object>;

    }