Skip to content

Instantly share code, notes, and snippets.

@TobiasSekan
Last active July 21, 2023 07:48
Show Gist options
  • Save TobiasSekan/73a93c2dfea4a051ff72abb5218d6f8f to your computer and use it in GitHub Desktop.
Save TobiasSekan/73a93c2dfea4a051ff72abb5218d6f8f to your computer and use it in GitHub Desktop.
[WPF] Fix for -> System.Windows.Data Error: 4 -> HorizontalContentAlignment and VerticalContentAlignment

Fix for debug output errors

Add the follow lines to the file App.xaml in your WPF application

    <!--
        Global fix for
        
        System.Windows.Data Error: 4 :
        Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''.
        BindingExpression:Path=HorizontalContentAlignment; DataItem=null;
        target element is 'ComboBoxItem' (Name='');
        target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
        
        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')
    -->
    
   <Application.Resources>
        <Style TargetType="ComboBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Left" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
        </Style>
    </Application.Resources>
@anders-eriksson
Copy link

First a big thank you!
This error is strange it complains about a combobox with no name. All my comboboxes has names. All my object has names to make it easier to find where the error is...

@Keke71
Copy link

Keke71 commented Jul 21, 2023

I had the same problem with a ListBox and a (temporarily) empty source. For me it was enough to just assign the default style:

<ListBox ItemContainerStyle="{StaticResource {x:Type ListBoxItem}}" .../>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment