-1

I'm currently working on a WPF-Input Window and now I have following problem:

if (e.Key == System.Windows.Input.Key.Enter)
{
     this.variantNumbers.Add(new VariantNumbers {Number = 
     txtVariantNo.Text});
     lstBoxVariants.ItemsSource = this.variantNumbers;
     lstBoxVariants.Visibility = Visibility.Visible;
     txtVariantNo.Text = "";
 }   

When I click enter, I want to update the ItemsSource of the ListBox whilst I am setting the ItemsSource new every time I add an element.

What could be wrong here, that my ListBox ignores this setting, the first time I click Enter, it works, the second and following times it doesn't.

Please let me know if someone of you knows what could be wrong here.

Thank You!

Lennart
  • 9,657
  • 16
  • 68
  • 84
Dev Knight
  • 95
  • 1
  • 9
  • It's by design, there is an performance optimization in setter `if(value != _value)` which simply ignores any of your further call. Try to set it to `null` first if you want to *refresh* the value. – Sinatr Sep 05 '18 at 11:12
  • @Sinatr This worked fine. Thank you for your help. – Dev Knight Sep 05 '18 at 11:15
  • 1
    Possible duplicate of [WPF ListView: Changing ItemsSource does not change ListView](https://stackoverflow.com/questions/20996288/wpf-listview-changing-itemssource-does-not-change-listview) – Sinatr Sep 05 '18 at 11:19
  • While this may work fine, it has a major drawback. The visual representation of all items is re-created each time you reset the ItemsSource. Don't do that. Use an ObservableCollection instead, as shown in the answer. – Clemens Sep 05 '18 at 19:56

1 Answers1

1

variantNumbers should be an ObservableCollection<VariantNumbers>. In this case you won't have to set ItemsSource each time you add new item.

private readonly ObservableCollection<VariantNumbers> variantNumbers =
    new ObservableCollection<VariantNumbers>();
...

lstBoxVariants.ItemsSource = variantNumbers;
...

if (e.Key == System.Windows.Input.Key.Enter)
{
    variantNumbers.Add(new VariantNumbers { Number = txtVariantNo.Text });
    txtVariantNo.Text = "";     
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
Access Denied
  • 8,723
  • 4
  • 42
  • 72