List<T> doesn't trigger any notifications, so the UI cannot detect when the contents of the list have changed.
I replace List<string> with ObservableCollection to update list data.
MainWindow.xaml:
<StackPanel x:Name="sp">
<TabControl x:Name="txtoriginal" ItemsSource="{Binding original, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TabControl x:Name="txtrandom_list" ItemsSource="{Binding random_list, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox x:Name="input" Background="AliceBlue" Height="40" Margin="5"/>
<Button x:Name="swap" Content="swap" Margin="5" Click="swap_Click" />
</StackPanel>
MainWindow.xaml.cs:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
namespace SwapAndSort
{
public partial class MainWindow : Window,INotifyPropertyChanged
{
public ObservableCollection<string> original { get; set; }
public ObservableCollection<string> random_list { get; set; }
public ObservableCollection<string> Random_list
{
get
{
return random_list;
}
set
{
random_list = value;
PropertyChanged(this, new PropertyChangedEventArgs("Random_list"));
}
}
public MainWindow()
{
InitializeComponent();
original = new ObservableCollection<string>() { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
Random random = new Random();
random_list = new ObservableCollection<string>(original.OrderBy(x => random.Next()).ToList());
DataContext=this;
}
public event PropertyChangedEventHandler PropertyChanged;
private void swap_Click(object sender, RoutedEventArgs e)
{
int index = Int32.Parse( input.Text);
string str = original[index];
int index1 = random_list.IndexOf(str);
random_list = (ObservableCollection<string>)random_list.Swap(index, index1);
}
}
public static class C
{
public static ObservableCollection<T> Swap<T>(this ObservableCollection<T> list, int indexA, int indexB)
{
T tmp = list[indexA];
list[indexA] = list[indexB];
list[indexB] = tmp;
return list;
}
}
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.