使用自定义控件排序列表
Sorting List with Custom Control
我想对包含自定义控件的列表进行排序。
该列表有一个 listboxitem 列表,里面有一个复选框,复选框里面有一个文本块。
List<ListBoxItem> listboxItem =new List<ListBoxItem>();
Some code that add the control into listboxItem with for loop
{
ListBoxItem lbi = new ListBoxItem();
CheckBox chkBox = new CheckBox();
TextBlock txtBlock = new TextBlock();
txtBlock.Text = sometext;
chkBox.Content = txtBlock;
lbi.Content = chkBox;
listBoxItems.Add(lbi);
}
listboxItems.Sort();
而且我已经实现了 IComparable 接口
public int CompareTo(Object obj)
{
if (obj == null) return 1;
List<ListBoxItem> listBoxItems = obj as List<ListBoxItem>;
for (int i = 0; i < listBoxItems.Count; i++)
{
if (i < listBoxItems.Count)
{
ListBoxItem listBoxItem = listBoxItems[i];
ListBoxItem lbi = this.listBoxItems[i];
CheckBox checkBox = listBoxItem.Content as CheckBox;
CheckBox chk = lbi.Content as CheckBox;
TextBlock textBlock = checkBox.Content as TextBlock;
TextBlock txt = chk.Content as TextBlock;
return string.Compare(txt.Text, textBlock.Text);
}
}
return 0;
}
它仍然给我错误,需要实现 Icomparable。
不确定它是否正确实现或使用,对于这个实现我来说很新 @.@
刚刚发现可以使用 Linq 和 Tag 来摆脱 IComparable。
编辑代码:
Some code that add the control into listboxItem with for loop
{
ListBoxItem lbi = new ListBoxItem();
CheckBox chkBox = new CheckBox();
TextBlock txtBlock = new TextBlock();
txtBlock.Text = sometext;
chkBox.Content = txtBlock;
lbi.Content = chkBox;
lbi.Tag = sometext;
listBoxItems.Add(lbi);
}
listBoxItems = listBoxItems.OrderBy(x => x.Tag).ToList();
然后,列表将按字母顺序完美排序。
我想对包含自定义控件的列表进行排序。 该列表有一个 listboxitem 列表,里面有一个复选框,复选框里面有一个文本块。
List<ListBoxItem> listboxItem =new List<ListBoxItem>();
Some code that add the control into listboxItem with for loop
{
ListBoxItem lbi = new ListBoxItem();
CheckBox chkBox = new CheckBox();
TextBlock txtBlock = new TextBlock();
txtBlock.Text = sometext;
chkBox.Content = txtBlock;
lbi.Content = chkBox;
listBoxItems.Add(lbi);
}
listboxItems.Sort();
而且我已经实现了 IComparable 接口
public int CompareTo(Object obj)
{
if (obj == null) return 1;
List<ListBoxItem> listBoxItems = obj as List<ListBoxItem>;
for (int i = 0; i < listBoxItems.Count; i++)
{
if (i < listBoxItems.Count)
{
ListBoxItem listBoxItem = listBoxItems[i];
ListBoxItem lbi = this.listBoxItems[i];
CheckBox checkBox = listBoxItem.Content as CheckBox;
CheckBox chk = lbi.Content as CheckBox;
TextBlock textBlock = checkBox.Content as TextBlock;
TextBlock txt = chk.Content as TextBlock;
return string.Compare(txt.Text, textBlock.Text);
}
}
return 0;
}
它仍然给我错误,需要实现 Icomparable。 不确定它是否正确实现或使用,对于这个实现我来说很新 @.@
刚刚发现可以使用 Linq 和 Tag 来摆脱 IComparable。
编辑代码:
Some code that add the control into listboxItem with for loop
{
ListBoxItem lbi = new ListBoxItem();
CheckBox chkBox = new CheckBox();
TextBlock txtBlock = new TextBlock();
txtBlock.Text = sometext;
chkBox.Content = txtBlock;
lbi.Content = chkBox;
lbi.Tag = sometext;
listBoxItems.Add(lbi);
}
listBoxItems = listBoxItems.OrderBy(x => x.Tag).ToList();
然后,列表将按字母顺序完美排序。