kmarks2
kmarks2

Reputation: 4875

Fix inability of a ComboBox to bind an observalbe collection

I have a ComboBox withing a GridView column:

...
            <GridView AllowsColumnReorder="True" ColumnHeaderToolTip="Info test">
               <GridViewColumn Header="Number" Width="120">
                  <GridViewColumn.CellTemplate>
                     <DataTemplate>
                        <ComboBox ItemsSource="{Binding Path=extensions}" Width="105" IsEditable="True" HorizontalAlignment="Center" Margin="0,0,0,0" BorderThickness="0">
                           <ComboBox.Resources>
                              <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">15</sys:Double>
                           </ComboBox.Resources>
                        </ComboBox>
                     </DataTemplate>
                  </GridViewColumn.CellTemplate>
               </GridViewColumn>
            </GridView>
...

In the code behind, "extensions" is an ObserverableCollection<string> that is 100% getting initialized and populated (this is in the class constructor):

public partial class MyForm : Window
{
   ...
   public ObservableCollection<string> extensions;
   ...

   public MyForm()
   {
      ...
      Initialize();
   }

   private Initialize()
   {
       extensions = new ObservableCollection<string>();
       extensions.Add("x100");
       extensions.Add("x101");
   }
}

But when the application runs while the comboboxes appear, the binding never happens. What additional step(s) are required for this to be complete/correct?

Upvotes: 1

Views: 67

Answers (1)

Mikl&#243;s Balogh
Mikl&#243;s Balogh

Reputation: 2202

First do not use public field, use properties instead. As far as I know public fields doesn't work with binding.

public ObservableCollection<string> extensions {get; private set;}

Second, probably the datacontext of the combobox is not set to the MyForm instance. Try this

<ComboBox ItemsSource="{Binding Path=extensions, RelativeSource={RelativeSource AncestorType={x:Type MyForm}}}" ... >

Upvotes: 2

Related Questions