项目未从列表中删除
这是我的代码:
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.
}
请建议我在这段代码中使用。
由于 阿米特
答案 0 :(得分:1)
您正在创建一个新的空列表,然后尝试删除位置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
的行。这就是导致代码失败的原因。
答案 1 :(得分:1)
在删除连接之前,您似乎正在替换连接列表。
由于您将此标记为WPF,我将假设您在某些时候可以从列表中删除该项目,但它仍然出现在屏幕上。试试这个:
if (a.Connections.Count > 0)
{
var newList = new List<IEmpConnection>(a.Connections);
a.Connections.RemoveAt(1);
a.Connections = newList;
}
或者,您可以使用ObservableCollection<IEmpConnection>
。这是一个特殊的集合,可在集合更改时引发事件。然后你可以简单地删除对象,屏幕就会更新。