对于我的Windows 8应用程序,我有一个如下所示的Listbox元素;当我在AppBar上按下multiselect图标时,我想在DataTemplate中显示复选框。这样,用户就可以对项目进行多选择。
我在这个列表框上绑定了50个元素,并且总是在索引11 ItemContainerGenerator.ContainerFromIndex上返回null,加上列表其余部分的一些其他项。因此,50项中大约有10项返回为null。
对于WPF有一些答案,比如应用Dispatcher.BeginInvoke或UpdateLayout,ScrollIntoView,但它们都不起作用。
另一方面,如果我滚动列表,然后按下AppBar图标,它就能正常工作。但是用户可以在数据绑定之后直接按下图标,他们不会看到一些复选框。
对于Windows 8的这个问题有什么解决办法吗?
<ListBox Name="ResultListBox" ItemsSource="{Binding}"
SelectionChanged="ResultListBox_OnSelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,10" Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<CheckBox Name="CheckBox" Visibility="Collapsed">
</CheckBox>
<Image Source="{Binding url}"
Width="125"
Height="125"
VerticalAlignment="Top"
Margin="0,0,5,0"></Image>
</StackPanel>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding title}"
VerticalAlignment="Top"
FontFamily="Portable User Interface"></TextBlock>
</StackPanel>
<StackPanel>
<TextBlock Text="{Binding description}"
FontFamily="Portable User Interface"></TextBlock>
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
void appBarButtonSelect_Click(object sender, EventArgs e)
{
//Dispatcher.BeginInvoke(delegate
//{
//});
for (int i = 0; i < ResultListBox.Items.Count; i++)
{
//ResultListBox.UpdateLayout();
//ResultListBox.ScrollIntoView(i);
DependencyObject item = ResultListBox.ItemContainerGenerator.ContainerFromIndex(i);
if (item != null)
{
CheckBox checkBox = FindFirstElementInVisualTree<CheckBox>(item);
if (checkBox != null)
{
checkBox.Visibility = Visibility.Visible;
}
}
else
{
Debugger.Break();
}
}
}发布于 2014-10-22 04:05:42
我认为你使用ScrollIntoView + UpdateLayout不正确,
当它需要一个与ItemsSource直接相关的对象时,您将向它传递一个索引
因此,如果您的ItemsSource是ObservableCollection,请执行以下操作:
object o = ((ObservableCollection<sample_model>)this.myListBox.ItemsSource)[INDEX];
this.myListBox.ScrollIntoView(o); // call this first
this.myListBox.UpdateLayout(); // call this second那么您的ItemContainerGenerator.ContainerFromIndex(INDEX)将不为空。
https://stackoverflow.com/questions/26499460
复制相似问题