BindingList and ListBox behaviour
I have a ListBox that is bound to a BindingList collection. This works great.
My only grief occurs when the first item enters the collection. The default behavior of the ListBox is to select that item - yet, this does not raise the SelectedIndexChanged event. I assume this is because the SelectedIndex is initially set to null; on becoming anything but null, the index isn't actually changed; rather assigned. How can I stop the default behavior of selecting (highlighting) the first initial item added to the ListBox?
If my assumption is wrong, please shed some light?
Update
Here is the core parts of my code thus far.
public UavControlForm()
{
InitializeComponent();
_controlFacade = new UavController.Facade.ControlFacade();
UpdateFlightUavListBox();
}
private void UpdateFlightUavListBox()
{
lsbFlightUavs.DataSource = _controlFacade.GetFlightUavTally();
lsbFlightUavs.DisplayMember = "Name";
}
private static BindingList<FlightUav> _flightUavTally = new BindingList<FlightUav>();
public BindingList<FlightUav> FlightUavTally
{
get { return _flightUavTally; }
}
public void AddFlightUav(double[] latLonAndAlt)
{
FlightUav flightUav = new FlightUav();
flightUav.Latitude = latLonAndAlt[0];
flightUav.Longitude = latLonAndAl开发者_运维技巧t[1];
flightUav.Altitude = latLonAndAlt[2];
_flightUavTally.Add(flightUav);
UtilStk.InjectAircraftIntoStk(flightUav.Name);
flightUav.SetFlightDefaults();
PlayScenario();
}
Update:
So, setting lsbFlightUavs.SelectedIndex = -1
solves the problem. The above method AddFlightUav()
is called from a button's OnClick handler in a second form from the main form. How can I call lsbFlightUavs.SelectedIndex = -1
from this second form when the AddFlightUav()
method returns? I know I can make the ListBox static, but that seems like bad practice to me.. what would be a more elegant solution?
Using WinForms, I implemented the Singleton pattern. This enabled me to access the ListBox control from my second form.
Form 1
private static UavControlForm _instance = new UavControlForm();
private UavControlForm()
{
InitializeComponent();
}
public static UavControlForm Instance
{
get { return _instance; }
}
public ListBox FlightUavListBox
{
get { return lsbFlightUavs; }
}
Form 2
UavControlForm.Instance.FlightUavListBox.SelectedIndex = -1;
精彩评论