question

hfaun-1603 avatar image
0 Votes"
hfaun-1603 asked ·

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

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-wpf
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

PeterFleischer-3316 avatar image
0 Votes"
PeterFleischer-3316 answered ·

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>
· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.