WPF, XAML, Combobox: Cannot find source for binding with reference

hfaun 1 Reputation point
2020-06-12T06:23:47.837+00:00

I have some comboboxes that use the same possible input values. Hence I tried to create a style and then set the style on my combo boxes. However, I am getting the error

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=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

My style is defined as

    <Window.Resources>
        <Style TargetType="{x:Type ComboBox}" x:Key="MyCombobox" xmlns:c="clr-namespace:System.Collections;assembly=mscorlib">
            <Setter Property="ItemsSource">
                <Setter.Value>
                    <c:ArrayList>
                        <ComboBoxItem>Item1</ComboBoxItem>
                        <ComboBoxItem>Item2</ComboBoxItem>
                        <ComboBoxItem>Item3</ComboBoxItem>
                    </c:ArrayList>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

Then my comboboxes are defined as

   <ComboBox x:Name="comboBox1" Text="{Binding Path=Input1}" Style="{StaticResource MyCombobox}" />
   <ComboBox x:Name="comboBox2" Text="{Binding Path=Input2}" Style="{StaticResource MyCombobox}" />

Input1 and Input2 are text properties in my VM. So why am I getting this error?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,762 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,321 Reputation points
    2020-06-12T06:51:32.247+00:00

    Hi, instead of ComboBoxItem as data typ use a simple data type like string:

      <Window.Resources>
        <Style TargetType="{x:Type ComboBox}" x:Key="MyCombobox" 
               xmlns:c="clr-namespace:System.Collections;assembly=mscorlib"
               xmlns:sys="clr-namespace:System;assembly=mscorlib">
          <Setter Property="ItemsSource">
            <Setter.Value>
              <c:ArrayList>
                <!--<ComboBoxItem>Item1</ComboBoxItem>
                <ComboBoxItem>Item2</ComboBoxItem>
                <ComboBoxItem>Item3</ComboBoxItem>-->
                <sys:String>Item1</sys:String>
                <sys:String>Item2</sys:String>
                <sys:String>Item3</sys:String>
              </c:ArrayList>
            </Setter.Value>
          </Setter>
        </Style>
      </Window.Resources>
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.