Question

I have a WPF application (.Net 4.5.1) where I create the items in a combo box dynamically, I bind to the ItemSource with an observable collection. But when I do this i get two binding errors, one for VeticalContentAlignment and one for HorizontalContentAlignment, for each item that I add.

System.Windows.Data Error: 4 : 
Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. 
BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ComboBoxItem' (Name='PhoneItem'); 
target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

I have googled and found some pointers that did not help, e.g. adding a global style

<Style TargetType="{x:Type ComboBoxItem}">
    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
 </Style>

or defining an inline container style in the combo box.

<ComboBox.ItemContainerStyle>
    <Style TargetType="ComboBoxItem">
       <Setter Property="HorizontalContentAlignment" Value="Left" />
       <Setter Property="VerticalContentAlignment" Value="Center" />
    </Style>
</ComboBox.ItemContainerStyle>

I can reproduce this in a clean project where I have no styling and only a combo box bound to an observable collection if anyone is interested in having a look at my stripped code.

Update 1 - My XAML and code behind

<Window x:Class="WpfApplicationDynamicComboBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>

            <Button Click="ButtonBase_OnClick" Margin="5">Load Combobox</Button>

            <ComboBox Name="DynamicComboBox"
                      ItemsSource="{Binding MyItems}"
                      Width="400"/>

        </StackPanel>
    </Grid>
</Window>


public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();

    DataContext = this;
    MyItems = new ObservableCollection<ComboBoxItem>();
    MyItems.Add( new ComboBoxItem {Content = string.Format( "Phone: {0}", "123" ), Name = "PhoneItem_" + DateTime.Now.Second} );
  }

  public ObservableCollection<ComboBoxItem> MyItems { get; set; }

  private void ButtonBase_OnClick( object sender, RoutedEventArgs e )
  {
    MyItems.Add( new ComboBoxItem {Content = string.Format( "Phone: {0}", "123" ), Name = "PhoneItem_" + DateTime.Now.Second} );
  }
}

Update 2 - Link to sample project http://bit.ly/1fwvgkZ

Any help getting rid of these errors are greatly appreciated!

Was it helpful?

Solution

Okay fixed your error. Just replace your code behind with

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;

        MyItems = new ObservableCollection<ComboBoxItem>();
        MyItems.Add(new ComboBoxItem
        {
            Name = "PhoneItem_" + DateTime.Now.Second,
            Content = string.Format("Phone: {0}", "123"),
            HorizontalContentAlignment = HorizontalAlignment.Left,
            VerticalContentAlignment = VerticalAlignment.Center
        });
    }


    public ObservableCollection<ComboBoxItem> MyItems { get; set; }

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        MyItems.Add(new ComboBoxItem
        {
            Name = "PhoneItem_" + DateTime.Now.Second,
            Content = string.Format("Phone: {0}", "123"),
            HorizontalContentAlignment = HorizontalAlignment.Left,
            VerticalContentAlignment = VerticalAlignment.Center
        });
    }


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top