我在Windows应用程序中有一个ListBox。在按钮操作中,我需要为ListBox中名为lb的每个lb设置转换和名称。
我的资料来源是
var items = new ObservableCollection<string>();
for (int i = 0; i < 10; ++i)
{
items.Add("Item " + i);
}
lb.ItemsSource = items;我有一个代码将一个RenderTransform添加到ListBox中的每个ListBoxItem中
for (int i = 0; i < items.Count;++i )
{
var item = this.lb.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
item.RenderTransform = new CompositeTransform();
item.Name = i.ToString() //needed for storybord
//another stuff
}而且工作正常。问题是,我首先需要将和项插入到列表中。当我在for循环之前调用items.Insert(index,"test")时,我会得到一个异常,当i==index时该项为null。插入新项并不重要,对于该项我总是获得null。
我做错了什么?或者在尝试访问ListBox之前,插入新项时是否需要等待ListBoxItem的事件?
编辑:我提取了代码并将其放入解决方案:https://dl.dropboxusercontent.com/u/73642/PhoneApp2.zip。我首先将一个假项目插入到新的解决方案中,然后淡出,然后使用动画将原始项目移动到该位置。
发布于 2013-04-12 22:09:13
等待调度程序完成它所做的工作,例如(由于添加了一个新项而更新UI )
this.Dispatcher.BeginInvoke(() =>
{
//Code Here
});如果您曾经操作过UI,比如在没有更新UI的情况下将项添加到列表框中,那么您将无法运行针对UI的代码。
编辑:这是你的项目工作的代码
private void Button_Click(object sender, RoutedEventArgs e)
{
start = Int32.Parse(from.Text);
end = Int32.Parse(to.Text);
fake = items[start];
//items.Insert(end, fake);
this.Dispatcher.BeginInvoke(() =>
{
for (int i = 0; i < items.Count; ++i)
{
var item = this.lb.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
item.Name = i.ToString();
}
(this.lb.ItemContainerGenerator.ContainerFromIndex(end) as ListBoxItem).RenderTransform = new CompositeTransform();
(this.lb.ItemContainerGenerator.ContainerFromIndex(end) as ListBoxItem).Name = "listBoxItem1";
(this.lb.ItemContainerGenerator.ContainerFromIndex(start) as ListBoxItem).Name = "listBoxItem";
sbListBox.Begin();
});
}发布于 2013-04-13 07:20:24
在条目添加之后,由于UI子系统的异步特性,不生成容器。尝试订阅ItemsChanged (或StatusChanged,对不起,我不记得了),并在使用适当的事件args触发事件时获取项。
https://stackoverflow.com/questions/15977431
复制相似问题