Skip to content

Instantly share code, notes, and snippets.

@TobiasSekan
Last active October 15, 2025 05:39
Show Gist options
  • Select an option

  • Save TobiasSekan/73a93c2dfea4a051ff72abb5218d6f8f to your computer and use it in GitHub Desktop.

Select an option

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>
@YetAnotherCodeMaker
Copy link

Thanks, this is still a fix as of today (.NET 9). In my case, the exceptions occur when I change the SortDescriptions of a CollectionViewSource at runtime and that makes the application totally unresponsive (the weird thing is it does not happen when the collection is first loaded, only when its sort order is modified).

@Rabina4363sf
Copy link

This solution fixes the problem when we use that style in Application Resources.
Why it doesn't work when we use that style in Grid or User Control resources ?

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