WinForms ComboBox 데이터 바인딩 문제
-
08-06-2019 - |
문제
당신이 다음과 같은 일을 하고 있다고 가정하자
List<string> myitems = new List<string>
{
"Item 1",
"Item 2",
"Item 3"
};
ComboBox box = new ComboBox();
box.DataSource = myitems;
ComboBox box2 = new ComboBox();
box2.DataSource = myitems
이제 해당 배열에 2개의 콤보 상자가 바인딩되어 있고 모든 것이 잘 작동합니다.그러나 하나의 콤보 상자 값을 변경하면 두 콤보 상자 모두 방금 선택한 항목으로 변경됩니다.
이제 나는 배열이 항상 참조로 전달된다는 것을 알고 있습니다(C를 배울 때 배웠습니다 :D). 그런데 왜 콤보 상자가 함께 변경됩니까?나는 콤보 상자 컨트롤이 컬렉션을 전혀 수정하고 있다고 생각하지 않습니다.
해결 방법으로 예상/원하는 기능을 달성하지 못합니까?
ComboBox box = new ComboBox();
box.DataSource = myitems.ToArray();
해결책
이는 닷넷 프레임워크에서 데이터 바인딩이 설정되는 방식과 관련이 있습니다. 특히 BindingContext
.높은 수준에서 이는 별도로 지정하지 않은 경우 각 양식과 양식의 모든 컨트롤이 동일함을 공유함을 의미합니다. BindingContext
.설정할 때 DataSource
재산 ComboBox
을 사용할 것이다 BindingContext
얻기 위해 ConcurrenyMangager
그게 목록을 마무리합니다.그만큼 ConcurrenyManager
목록에서 현재 선택된 위치 등을 추적합니다.
설정하면 DataSource
두 번째 ComboBox
그것은 같은 것을 사용할 것입니다 BindingContext
(양식) 동일한 내용을 참조할 수 있습니다. ConcurrencyManager
위와 같이 데이터 바인딩을 설정하는 데 사용되었습니다.
더 자세한 설명을 보려면 참조하세요. 바인딩컨텍스트.
다른 팁
더 나은 해결 방법(데이터 소스의 크기에 따라 다름)은 두 가지를 선언하는 것입니다. BindingSource
개체(2.00부터 새로 추가됨)는 컬렉션을 해당 개체에 바인딩한 다음 해당 개체를 콤보박스에 바인딩합니다.
완전한 예를 첨부합니다.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private BindingSource source1 = new BindingSource();
private BindingSource source2 = new BindingSource();
public Form1()
{
InitializeComponent();
Load += new EventHandler(Form1Load);
}
void Form1Load(object sender, EventArgs e)
{
List<string> myitems = new List<string>
{
"Item 1",
"Item 2",
"Item 3"
};
ComboBox box = new ComboBox();
box.Bounds = new Rectangle(10, 10, 100, 50);
source1.DataSource = myitems;
box.DataSource = source1;
ComboBox box2 = new ComboBox();
box2.Bounds = new Rectangle(10, 80, 100, 50);
source2.DataSource = myitems;
box2.DataSource = source2;
Controls.Add(box);
Controls.Add(box2);
}
}
}
자신을 더욱 혼란스럽게 만들고 싶다면 항상 생성자에서 바인딩을 선언해 보세요.이로 인해 일부 결과가 발생할 수 있습니다. 정말 호기심 많은 버그가 있으므로 항상 Load 이벤트에 바인딩합니다.