Ralt
Ralt

Reputation: 2124

Combobox binding breaks when dropped down

I have a ComboBox which is bound to a DependencyProperty on my form. I can add items to this property through a Button click and it will add them to the ComboBox. However, as soon as I drop down the ComboBox the binding breaks. I can still add items to the property, but my ComboBox never updates to show them.

For example

Starting the application again and:

XAML

<Grid x:Name="LayoutRoot"
      Background="White">
    <ComboBox Name="combTest"
              ItemsSource="{Binding Users}"
              Width="50"
              Height="50"
              HorizontalAlignment="Left" />
    <Button Click="ButtonBase_OnClick"
            Width="50"
            Height="50"
            HorizontalAlignment="Right" />
</Grid>

Code Behind

public MainPage()
{
    InitializeComponent();
    this.DataContext = this;
}

public static readonly DependencyProperty UsersProperty = DependencyProperty.Register(
 "Users", typeof (List<string>), typeof (MainPage), new PropertyMetadata(new List<string>()));

public List<string> Users
{
    get { return (List<string>) GetValue(UsersProperty); }
    set { SetValue(UsersProperty, value); }
}

private int i = 0;

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
   Users.Add("User " + i++);
}

Upvotes: 0

Views: 39

Answers (1)

daniel
daniel

Reputation: 1070

Use ObservableCollection instead of List

ObservableCollection would raise property change of adding and removing item in the collection, but List not.

Upvotes: 6

Related Questions