更改列表框中选定的项目时,我收到一个奇怪的错误,更改的项目显示为选中,但我无法取消选择或重新选择它。
有办法解决这个问题吗?
这是一个演示该问题的示例应用程序。
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.DataContext = new WindowViewModel();
lst.SelectedIndex = 0;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((WindowViewModel)this.DataContext).Items[0] = "New Item";
}
}
public class WindowViewModel
{
public WindowViewModel()
{
Items = new ObservableCollection<string>();
Items.Add("Item1");
Items.Add("Item2");
Items.Add("Item3");
}
public ObservableCollection<string> Items { get; set; }
}
<Window x:Class="WpfSelectionIssue.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<Button Content="Change" Click="Button_Click" />
<ListBox x:Name="lst" ItemsSource="{Binding Items}" />
</StackPanel>
</Window>
ImageOfIssue http://img136.imageshack.us/img136/9396/wpfselectionissue.jpg
最佳答案
经过一番搜索,我找到了解决方案。将 IsSynchronizedWithCurrentItem 添加到 ListBox 解决了该问题。
<ListBox
x:Name="lst"
ItemsSource="{Binding Items}"
IsSynchronizedWithCurrentItem="True"
/>
关于c# - 更改项目时的 WPF 列表框选择问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/855920/