对ListBoxItem进行排序 ListBox排序 调整ListBoxItem的顺序 上下移动ListBoxItem的顺序
界面如图:
xaml代码:
<Window x:Class="datagriddemo.SortListboxItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SortListboxItem" Height="283" Width="407">
<Grid>
<ListBox Height="114" HorizontalAlignment="Left" Margin="76,56,0,0" Name="listBox1" VerticalAlignment="Top" Width="107" >
<ListBoxItem Content="1"/>
<ListBoxItem Content="4"/>
<ListBoxItem Content="2"/>
<ListBoxItem Content="3"/>
</ListBox>
<Button Content="上移" Height="23" HorizontalAlignment="Left" Margin="205,86,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<Button Content="下移" Height="23" HorizontalAlignment="Left" Margin="205,129,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="button2_Click" />
</Grid>
</Window>
C# code:
using System.Windows;
using System.Windows.Controls;
namespace datagriddemo
{
/// <summary>
/// SortListboxItem.xaml 的交互逻辑
/// </summary>
public partial class SortListboxItem : Window
{
public SortListboxItem()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
//move up
string t = listBox1.SelectedItem.ToString();
int allitms=listBox1.Items.Count;
int selectedindex=listBox1.SelectedIndex;
if (selectedindex == 0)
return;
ListBoxItem[] lbis=new ListBoxItem[allitms];
ListBoxItem temp = new ListBoxItem();
for (int i = 0; i < allitms;i++ )
{
lbis[i] = (ListBoxItem)listBox1.Items[i];
}
temp = lbis[selectedindex-1];
lbis[selectedindex - 1] = lbis[selectedindex];
lbis[selectedindex] = temp;
listBox1.Items.Clear();
for (int j = 0; j < allitms;j++ )
{
listBox1.Items.Add(lbis[j]);
}
listBox1.SelectedItem = listBox1.Items[selectedindex-1];
listBox1.Focus();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
//move down
string t = listBox1.SelectedItem.ToString();
int allitms = listBox1.Items.Count;
int selectedindex = listBox1.SelectedIndex;
if (selectedindex == allitms-1)
return;
ListBoxItem[] lbis = new ListBoxItem[allitms];
ListBoxItem temp = new ListBoxItem();
for (int i = 0; i < allitms; i++)
{
lbis[i] = (ListBoxItem)listBox1.Items[i];
}
temp = lbis[selectedindex + 1];
lbis[selectedindex + 1] = lbis[selectedindex];
lbis[selectedindex] = temp;
listBox1.Items.Clear();
for (int j = 0; j < allitms; j++)
{
listBox1.Items.Add(lbis[j]);
}
listBox1.SelectedItem = listBox1.Items[selectedindex+1];
listBox1.Focus();
}
}
}