Why does my combobox freeze when the itemssource changes?
Steps to Reporoduce:
When the app starts, open the combobox so the items get generated. Now click the "Click Me!" button. In the code behind, the itemssource of the combobox is changed. Now try to open the combobox again. The combobox freezes for at least 5 seconds even though only 2 items are in the bound collection. This is just a test app. In my real application, there are more than 2 items and the lag is unbearable. I've tried this with virtualizing on and off. It makes no开发者_StackOverflow社区 difference.
What is taking so long? How do I fix this? If there's no direct fix, is there a work around?
XAML:
<StackPanel>
<ComboBox x:Name="cbo" DisplayMemberPath="Junk1"></ComboBox>
<Button Content="Click Me!" Click="btn_Click"></Button>
</StackPanel>
CODE:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
ObservableCollection<Junk> junk1 = new ObservableCollection<Junk>() {
new Junk() { Junk1 = "jdkf", Junk2 = "fjdfkasjd;klfj" },
new Junk() { Junk1 = "jfdk;a", Junk2 = "fjkdljf" } };
ObservableCollection<Junk> junk2 = new ObservableCollection<Junk>() {
new Junk() { Junk1 = "fjkdfhsdjk", Junk2 = "fdjkah;" },
new Junk() { Junk1="", Junk2 = "asdfj" } };
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
this.cbo.ItemsSource = junk1;
}
private void btn_Click(object sender, RoutedEventArgs e)
{
if (this.cbo.ItemsSource == junk1)
this.cbo.ItemsSource = junk2;
else
this.cbo.ItemsSource = junk1;
this.cbo.UpdateLayout();
}
}
public class Junk
{
public string Junk1 { get; set; }
public string Junk2 { get; set; }
}
myermian - No other events are wired. This is the entire application. There is no other code required to get the freezing behavior.
Aaron - Junk is just a standard class. It does not derive from anything. I have tried keeping the collection, calling the .Clear() method and then adding the new items. I get the exact same behavior.
AnthonyWJones - The bug is in WPF. I hadn't tried it in Silverlight. Sorry for the confusion.
I have copied your code exactly, and it runs perfectly as expected - so I suggest there may be something wrong with your environment.
Note : you do not need to call this.cbo.UpdateLayout();
as ItemsSource
is a dependency property and will update the control automatically when changed.
精彩评论