项目未从列表中删除
本文关键字:删除 列表 项目 | 更新日期: 2023-09-27 17:59:46
项目未从列表中删除
这是我的代码:
public interface IEmpConnection
{
int SegId { get; set; }
}
public class EmpConnection : IEmpConnection
{
private int segid;
public int SegId
{
get
{
return segid;
}
set
{
segid = value;
}
}
}
public class CustomerConnection : EmpConnection, ICustomerConnection
{
private int _id;
public int Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
}
public interface ICustomerConnection
{
int Id { get; set; }
}
public class CustConn : CustomerConnection
{
private ObservableCollection<CustomerConnection> _airSeg;
public CustConn()
{
_airSeg = new System.Collections.ObjectModel.ObservableCollection<CustomerConnection>();
_airSeg.Add(new AirSegmentConnection { Id = 1, SegId = 2 });
_airSeg.Add(new AirSegmentConnection { Id = 1, SegId = 3 });
}
private bool isDeleted;
public bool IsDeleted
{
get { return isDeleted; }
set { isDeleted = value; }
}
private List<IEmpConnection> _connection;
public List<IEmpConnection> Connections
{
get
{
var s = new AirSegmentConnection();
var k = s as ISegmentConnection;
if (IsDeleted)
{
_airSeg.RemoveAt(1);
}
return _connection = _airSeg.ToList().Cast<ISegmentConnection>().ToList();
//return _airSeg.ToList().Cast<ISegmentConnection>().ToList();
}
set
{
_connection = value;
//_airSeg = new System.Collections.ObjectModel.ObservableCollection<ISegmentConnection>(value.ToList()) ;
}
}
private ObservableCollection<CustomerConnection> airConnection;
public ObservableCollection<CustomerConnection> AirConnection
{
get { return _airSeg; }
set { _airSeg = value; }
}
}
在主上
按钮单击项目未被删除。请告诉我哪里做错了。
CustConn a = new CustConn();
if (a.Connections.Count > 0)
{
a.Connections = new List<IEmpConnection>();
a.Connections.RemoveAt(1);// this item is not being removed.
}
请建议我在这个代码中工作。
谢谢Amit
似乎是在删除连接之前替换连接列表。
由于您已经将其标记为WPF,我将假设在某个时候您能够从列表中删除该项目,但它仍然出现在屏幕上。试试这个:
if (a.Connections.Count > 0)
{
var newList = new List<IEmpConnection>(a.Connections);
a.Connections.RemoveAt(1);
a.Connections = newList;
}
或者,您也可以使用ObservableCollection<IEmpConnection>
。这是一个特殊的集合,在集合更改时引发事件。然后你只需简单地删除对象,屏幕就会更新。
您正在创建一个新的空列表,然后试图删除位置1处的元素。事实上,您刚刚覆盖了原始列表。
if (a.Connections.Count > 0)
{
/// REMOVE THIS LINE a.Connections = new List<IEmpConnection>();
a.Connections.RemoveAt(1);// this item is not being removed.
}
我注释掉的行创建了一个新列表,并在您尝试删除该项目之前覆盖a.Connections
。这就是导致代码失败的原因。