![](/img/trans.png)
[英]Bind to SelectedItems from DataGrid or ListBox in MVVM
[英]How to bind WinForm's listbox selecteditems
我有一個“所有選擇”的列表框,以及一個對所有這些選擇都為0的對象(因此具有多值選擇模式的列表框)。 我需要選擇在該列表框中選擇的所有對象選擇。
因此,我將ListBox.Datasource綁定到所有可用選項的列表,並試圖找到一種方法來將該對象選項綁定到Listbox SelectedItems屬性,但是我沒有找到有關如何執行此操作的任何信息。
假設我們有3個表格:“學生”,“課程”和“學生課程”。 因此,在“學生”表單中,我需要一個包含所有可用課程的列表框,並在該列表中選擇“學生課程”表中的所有“學生”課程。
是否有可能使用數據綁定來實現?
//1. getting the available list
List.DataSource = ..the list of all the courses
List.DisplayMember = "Name";
List.ValueMember = "Id";
//2. selecting the appropriate items in the list
List.SelectedItems.Clear();
foreach (var c in student.StudentsCourses)
{
//in this strange case Id is equal to the index in the list...
List.SetSelected(c.CourseId, true);
}
//instead of this "2." part I was hoping to use something like this:
List.DataBindings.Add("SelectedItems", student.StudentsCourses, "CourseId");
但是當我嘗試這樣做時,我收到一個錯誤: 無法綁定到屬性“ SelectedItems”,因為它是只讀的
我不確定我是否正確,但如果我做到了,是的,您可以做到。
例如:
List<KeyValuePair<string, Course>> coursesList = new List<KeyValuePair<string, Course>>();
List<Course> cList = // Get your list of courses
foreach (Course crs in cList)
{
KeyValuePair<string, Course> kvp = new KeyValuePair<string, Course>(crs.Name, crs);
cList.Add(kvp);
}
// Set display member and value member for your listbox as well as your datasource
listBox1.DataSource = coursesList;
listBox1.DisplayMember = "Key"; // First value of pair as display member
listBox1.ValueMember = "Value"; // Second value of pair as value behind the display member
var studentsList = // Get your list of students somehow
foreach (Student student in studentsList)
{
foreach (KeyValuePair<string, Course> item in listBox1.Items)
{
// If students course is value member in listBox, add it to selected items
if (student.Course == item.Value)
listBox1.SelectedItems.Add(item);
}
}
希望你從中得到邏輯。 由於您提供的代碼為零,因此我再也無法為您提供幫助。 干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.