I'm implementing a ComboBox that can be refreshed by users using a button. I'm trying to make it so that the previously selected item is automatically reselected if still present inside the ComboBox after a refresh.
MainWindow.xaml:
<ComboBox Canvas.Left="10" Canvas.Top="10" DisplayMemberPath="Name" IsEnabled="{Binding Path=Enabled}" ItemsSource="{Binding Path=Items}" SelectedItem="{Binding Mode=TwoWay, Path=SelectedItem}" Width="379"/>
<Button Content="{x:Static p:Resources.TextRefresh}" Canvas.Right="10" Canvas.Top="10" Click="OnClickButtonRefresh" Width="75"/>
MainWindow.xaml.cs:
public MainWindow()
{
InitializeComponent();
DataContext = m_BrowserInstances = new BrowserInstancesViewModel();
}
private void OnClickButtonRefresh(Object sender, RoutedEventArgs e)
{
m_BrowserInstances.Populate();
}
[EDITED TO CURRENT VERSION] BrowserInstancesViewModel.cs:
public sealed class BrowserInstancesViewModel : ViewModel
{
private Boolean m_Enabled;
public Boolean Enabled
{
get { return m_Enabled; }
}
private BrowserInstance m_SelectedItem;
public BrowserInstance SelectedItem
{
get { return m_SelectedItem; }
set
{
if (m_SelectedItem != value)
{
m_SelectedItem = value;
NotifyPropertyChanged("SelectedItem");
}
}
}
private ObservableCollection<BrowserInstance> m_Items;
public ObservableCollection<BrowserInstance> Items
{
get { return m_Items; }
}
public BrowserInstancesViewModel()
{
Populate();
}
private static Func<BrowserInstance, Boolean> Recover(BrowserInstance selectedItem)
{
return x =>
{
Process currentProcess = x.Process;
Process selectedProcess = selectedItem.Process;
if (currentProcess.Id != selectedProcess.Id)
return false;
if (currentProcess.MainModule.BaseAddress != selectedProcess.MainModule.BaseAddress)
return false;
if (currentProcess.MainWindowTitle != selectedProcess.MainWindowTitle)
return false;
return true;
};
}
public void Populate()
{
BrowserInstance item = m_SelectedItem;
List<BrowserInstance> items = new List<BrowserInstance>();
foreach (Process process in Process.GetProcessesByName("chrome"))
items.Add(new BrowserInstance(process));
if (items.Count > 0)
{
m_Enabled = true;
m_Items = new ObservableCollection<BrowserInstance>(items.OrderBy(x => x.Process.Id));
if (item != null)
m_SelectedItem = m_Items.SingleOrDefault(Recover(item));
if (m_SelectedItem == null)
m_SelectedItem = m_Items[0];
}
else
{
m_Enabled = false;
m_Items = new ObservableCollection<BrowserInstance>();
m_Items.Add(new BrowserInstance());
m_SelectedItem = m_Items[0];
}
NotifyPropertyChanged("Enabled");
NotifyPropertyChanged("Items");
NotifyPropertyChanged("SelectedItem");
}
}
I can get back the previously selected item, but only sometimes. Looks like the code is not working properly when I need to select a default value (Index 0) if the previous selected item cannot be recovered.