簡単な答えは、クリックされたボタンの親を取得することです。その親は、スタック パネルである必要があります。
次に、スタック パネルを取得したら、そのオブジェクトをリスト ボックスの get index メソッドにフィードできます。インデックスを取得したら、簡単です。検索とスイッチのアルゴリズムの模造品を使って切り替えるだけです。
XAML
<Window x:Class="sptest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox Name="mylb">
</ListBox>
</Grid>
</Window>
CSファイル
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
for (int x = 0; x < 10; x++)
{
StackPanel sp = new StackPanel();
Button upbt = new Button();
Button dwbt = new Button();
upbt.Click += bt_Click;
dwbt.Click+= bt_Click;
upbt.Tag = "up";
dwbt.Tag = "down";
upbt.Content = "Up";
dwbt.Content = "Down";
sp.Orientation = Orientation.Vertical;
sp.Children.Add(upbt);
sp.Children.Add(dwbt);
mylb.Items.Add(sp);
}
}
void bt_Click(object sender, RoutedEventArgs e)
{
Button but = (sender as Button);
var par = but.Parent;
string tag = but.Tag.ToString();
if (par is StackPanel)
{
StackPanel sp = (par as StackPanel);
int index = mylb.Items.IndexOf(sp);
List<StackPanel> items = new List<StackPanel>();
foreach (StackPanel item in mylb.Items)
{
items.Add(item);
}
if (but.Tag == "up")
{
if (index != 0)
{
StackPanel temp = items[index - 1];
items[index - 1] = items[index];
items[index] = temp;
}
}
else
{
if (index != items.Count)
{
StackPanel temp = items[index + 1];
items[index + 1] = items[index];
items[index] = temp;
}
}
mylb.Items.Clear();
foreach (StackPanel item in items)
{
mylb.Items.Add(item);
}
}
}
}
このコードはコンパイルおよび実行されているため、開始点として適しています。
これは、複雑で非推奨な方法です。データバインディングなど、それほど複雑ではなく、より専門的な方法があります。
本当にエリートになりたい場合は、リストボックスへのデータバインディングを調べてください。
基本的に何が起こるかというと、すべてのオブジェクトを作成し、それらを観察可能なコレクションに入れることです。次に、手動でリストボックスに物をクリアして再追加する代わりに、コレクションを操作するだけです。
文字列の ObservableCollection への ListBox の単純な WPF DataBinding