2

我的 WPF C# 程序有一个列表框,其中包含用户可以操作的项目:更改顺序、复制/粘贴等。目前,当我在列表框中选择一个项目,然后单击上移按钮时,该项目将向上移动列表,但该项目不再突出显示或选择。因此,如果不重新选择列表框项,我将无法进行连续操作。

如何强制我的列表框保留它的选择和突出显示?

4

2 回答 2

1

如果它被选中但默认没有焦点,它会失去颜色

<Style.Resources>
    <!-- Background of selected item when focussed -->
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                     Color="Green"/>
    <!-- Background of selected item when not focussed -->
    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
                     Color="LightGreen" />
</Style.Resources> 
于 2012-11-05T19:35:31.363 回答
1

我会将 ListBox 的 ItemsSource 绑定到 ObservableCollection。然后您可以操作 ObservableCollection 并且 ListBox 将为您更新。这是一个例子:

XAML:

<Window x:Class="ListBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ListBox="clr-namespace:ListBox" Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <ListBox:ListBoxViewModel />
    </Window.DataContext>
    <StackPanel>
        <Button Command="{Binding Up}">Up</Button>
        <Button Command="{Binding Down}">Down</Button>
        <ListBox Grid.Column="0" ItemsSource="{Binding Items}" SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}" />
    </StackPanel>
</Window>

和代码:

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;

namespace ListBox
{
    public class ListBoxViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public ObservableCollection<string> Items {get; private set; }

        private void ExecuteUp()
        {
            if (SelectedIndex == 0)
                return;
            Items.Move(SelectedIndex, SelectedIndex - 1);
        }
        private void ExecuteDown()
        {
            if (SelectedIndex >= Items.Count - 1)
                return;
            Items.Move(SelectedIndex, SelectedIndex + 1);
        }

        public ICommand Up { get; private set; }
        public ICommand Down { get; private set; }

        private int m_SelectedIndex = 0;
        public int SelectedIndex
        {
            get { return m_SelectedIndex; }
            set
            {
                m_SelectedIndex = value;
                OnPropertyChanged("SelectedIndex");
            }
        }

        public ListBoxViewModel()
        {
            Items = new ObservableCollection<string>() {"London", "Paris", "Berlin"};
            Up = new RelayCommand(ExecuteUp);
            Down = new RelayCommand(ExecuteDown);
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
于 2012-11-06T12:24:20.593 回答