3

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.

4

1 回答 1

3

您需要设置m_SelectedItem为找到的项目SingleOrDefault(Recover(...))

目前,您将其设置为旧实例。该实例不再存在于列表中,显然您的BrowserInstance类没有实现任何相等成员。

根据您当前的代码正确代码:

if(selectedItem != null)
    m_SelectedItem = m_Items.SingleOrDefault(Recover(selectedItem));
if(m_SelectedItem == null)
    m_SelectedItem = m_Items[0];

更新:

您上传的代码有两个问题。

  1. 如果没有进程,您添加Process的默认对象的属性值为. 这导致. 通过将前面更改为来修复它BrowserInstancenullNullReferenceExceptionSingleOrDefault
    if

    if(selectedItem != null && selectedItem.Process != null)
    
  2. Populate方法结束时,您引发PropertyChanged事件Items- 更新组合框中的值 - 以及SelectedItem- 将所选项目设置为用户先前选择的项目。
    这里的问题是 WPF 将在引发时更新SelectedItem,因为它在新项目列表中找不到先前选择的项目。这有效地覆盖了您在方法中计算的新选定项。 通过不将新选定的项目分配给但在引发事件后将该 值分配给来修复它:nullPropertyChangedItemsPopulate
    m_SelectedItemselectedItemSelectedItemPropertyChangedItems

    public void Populate()
    {
        BrowserInstance selectedItem = 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 (selectedItem != null && selectedItem.Process != null)
                selectedItem = m_Items.SingleOrDefault(x => (x.Process.Id == selectedItem.Process.Id) && (x.Process.MainModule.BaseAddress == selectedItem.Process.MainModule.BaseAddress));
    
            if (selectedItem == null)
                selectedItem = m_Items[0];
        }
        else
        {
            m_Enabled = false;
    
            m_Items = new ObservableCollection<BrowserInstance>();
            m_Items.Add(new BrowserInstance());
    
            selectedItem = m_Items[0];
        }
    
        NotifyPropertyChanged("Enabled");
        NotifyPropertyChanged("Items");
        SelectedItem = selectedItem;
    }
    

如果您能正确实现相等,BrowserInstance则可以使用 WPF 功能来保留当前选定的项目。
的代码Populate可以简化如下:

public void Populate()
{
    BrowserInstance selectedItem = m_SelectedItem;
    List<BrowserInstance> items = new List<BrowserInstance>();

    foreach (Process process in Process.GetProcessesByName("chrome"))
        items.Add(new BrowserInstance(process));

    m_Enabled = items.Any();
    m_Items = new ObservableCollection<BrowserInstance>(items.OrderBy(x => x.Process.Id));
    if(!m_Enabled)
        m_Items.Add(new BrowserInstance());

    NotifyPropertyChanged("Enabled");
    NotifyPropertyChanged("Items");
    if (SelectedItem == null)
        SelectedItem = m_Items[0];
}

的相等实现BrowserInstance如下所示:

public sealed class BrowserInstance : IEquatable<BrowserInstance>
{

    // ...

    public bool Equals(BrowserInstance other)
    {
        if (ReferenceEquals(null, other))
            return false;
        if (ReferenceEquals(this, other))
            return true;
        if (m_Process == null)
        {
            if (other.m_Process == null)
                return true;
            return false;
        }

        if (other.m_Process == null)
            return false;

        return m_Process.Id == other.m_Process.Id && m_Process.MainModule.BaseAddress == other.m_Process.MainModule.BaseAddress;
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as BrowserInstance);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return m_Process != null ? ((m_Process.Id.GetHashCode() * 397) ^ m_Process.MainModule.BaseAddress.GetHashCode()) : 0;
        }
    }
}
于 2013-04-23T12:58:29.487 回答