我有一个具有以下样式的surfacelistbox:
<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>
我通过代码填充此surfacelistbox,然后添加“全部显示”项:
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:路径= HorizontalContentAlignment;的DataItem = NULL; target元素是'SurfaceListBoxItem'(Name =''); target属性是'HorizontalContentAlignment'(类型'HorizontalAlignment')
如果我没有通过代码将IsSelected
设置为true
而是点击某个项目,那么一切都很好。有什么想法吗?
答案 0 :(得分:0)
由于您没有提供使用代码选择项目的代码,我不知道您是否正在使用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;
如果您对要选择的项目有引用,则使用第一种方法;如果您只知道提供列表中的索引,则使用第二种方法。
让我知道它是否适合你。
叶兰。