Cam*_*and 2 .net c# wpf xaml listbox
更改列表框中的所选项目时,出现一个奇怪的错误,其中更改的项目显示为选中状态,但无法取消选择或重新选择它。
有没有办法解决这个问题?
这是一个演示该问题的示例应用程序。
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>
Run Code Online (Sandbox Code Playgroud)
ImageOfIssue http://img136.imageshack.us/img136/9396/wpfselectionissue.jpg
经过更多搜索后,我找到了解决方案。向列表框添加IsSynchronizedWithCurrentItem解决了该问题。
<ListBox
x:Name="lst"
ItemsSource="{Binding Items}"
IsSynchronizedWithCurrentItem="True"
/>
Run Code Online (Sandbox Code Playgroud)