我有一个具有以下样式的表面列表框:
<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>
我正在通过代码填充这个表面列表框,然后添加一个“显示全部”项:
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
}
一切正常,在我通过代码设置IsSelected
为之前我没有收到任何错误。true
然后我得到这个错误:
System.Windows.Data 错误:4:找不到与引用“RelativeSource FindAncestor,AncestorType='System.Windows.Controls.ItemsControl',AncestorLevel='1''的绑定源。BindingExpression:Path=HorizontalContentAlignment; 数据项=空;目标元素是'SurfaceListBoxItem'(名称='');目标属性是“HorizontalContentAlignment”(类型“HorizontalAlignment”)
如果我不通过代码设置IsSelected
而是true
单击一个项目,一切都很好。有任何想法吗?