我有一个具有以下风格的表面镜盒:
<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之前,不会出现任何错误。然后我得到这个错误:
AncestorType='System.Windows.Controls.ItemsControl',System.Windows.Data错误:4:无法找到引用'RelativeSource FindAncestor,RelativeSource AncestorLevel=‘1’绑定的源代码。BindingExpression:Path=HorizontalContentAlignment;DataItem=null;目标元素是'SurfaceListBoxItem‘(Name='');目标属性是'HorizontalContentAlignment’(键入'HorizontalAlignment')
如果我不通过代码将IsSelected设置为true,而是单击某一项,那么一切都很好。有什么想法吗?
发布于 2012-08-21 05:19:23
因为您没有提供使用代码选择项目的代码,所以我不知道您是在使用MVVM,还是使用后面的代码,或者您是否已经尝试过以下方法。
我遵循了您的场景,并使用“ItemContainerGenerator”从代码中选择了一个项:
// Selecting an item given the actual item
object requestedItem = null; // TODO - You should set here the actual item
SurfaceListBoxItem itemContainer = itemsList.ItemContainerGenerator.ContainerFromItem(requestedItem) as SurfaceListBoxItem;
itemContainer.IsSelected = true;
// Selecting an item given his index in the item source
SurfaceListBoxItem itemContainer2 = itemsList.ItemContainerGenerator.ContainerFromIndex(2) as SurfaceListBoxItem;
itemContainer2.IsSelected = true;如果对要选择的项具有引用,则使用第一种方法;如果只知道所提供列表中的索引,则使用第二种方法。
如果对你有用就告诉我。
伊兰。
https://stackoverflow.com/questions/12044632
复制相似问题