我的WPF C#程序有一个列表框,其中包含用户可以操作的项目:更改顺序,复制/粘贴等。当前,当我在列表框中选择一个项目,然后单击上移按钮,该项目将向上移动列表,但随后不再突出显示或选择该项目。因此,如果不重新选择列表框项,我无法进行连续操作。
如何强制我的列表框保留其选择和突出显示?
答案 0 :(得分:0)
如果已选中,但默认情况下没有焦点,则会丢失颜色
<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>
答案 1 :(得分:0)
我将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));
}
}
}