I have a surfacelistbox with the following style:
<s:SurfaceListBox.ItemContainerStyle>
<Style TargetType="s:SurfaceListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontWeight" Value="Normal" />
<Setter Property="RenderTransformOrigin" Value="0.5,0.5" />
<Setter Property="MinHeight" Value="30" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type s:SurfaceListBoxItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="#FF7E0123" />
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleX="1.25" ScaleY="1.25"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</s:SurfaceListBox.ItemContainerStyle>
I am populating this surfacelistbox through code and then adding a "Show All" item:
private void AddShowAllCategories(int totalItems)
{
SurfaceListBoxItem CategoriesListBoxItem = new SurfaceListBoxItem();
CategoriesListBox.Items.Insert(0, CategoriesListBoxItem);
CategoriesListBoxItem.Content = "Show All " + "(" + totalItems + ")";
CategoriesListBoxItem.Margin = new Thickness(0,30,0,0);
CategoriesListBoxItem.IsSelected = true; //This is what is causing the issue
}
Everything works fine and I get no errors until I set the IsSelected to true through code. I then get this error:
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 'SurfaceListBoxItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
If I dont set IsSelected to true through code and instead click on an item, everything is fine. Any ideas?