清楚listbox绑定数据 ,然后再增加listbox数据绑定时会卡界面
贴上代码:
XAML部分:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="2*" />
</Grid.RowDefinitions>
<ListBox x:Name="searchcontact" Grid.RowSpan="2" Margin="0,0,0,124" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="displayname" FontSize="35" Text="{Binding Displayname}"/>
<TextBlock Name="phonenum" Text="{Binding PhoneNum}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid Grid.Row="1" Margin="-12,0">
<Button x:Name="buttonKeyPad1" Margin="0,272,1,1" UseLayoutRounding="True" Click="buttonKeyPad_Click">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="50">
<Run Text="Add"/>
</TextBlock>
<TextBlock Margin="10,0,0,0" Foreground="Gray" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="15" MinWidth="25"/>
</StackPanel>
</Button>
</Grid>
</Grid>
cs页代码:
public class Person
{
public string Displayname { get; set; }
public string PhoneNum { get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
ObservableCollection<Person> plist = new ObservableCollection<Person>();
// 构造函数
public MainPage()
{
InitializeComponent();
searchcontact.ItemsSource = plist;
// 用于本地化 ApplicationBar 的示例代码
//BuildLocalizedApplicationBar();
}
private void buttonKeyPad_Click(object sender, RoutedEventArgs e)
{
ThreadPool.QueueUserWorkItem((o) =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
plist.Clear();
}));
for (int i = 0; i < 40; i++)
{
Person p = new Person();
p.Displayname = String.Format("姓名{0}", i + 1);
p.PhoneNum = String.Format("电话{0}", i + 1);
this.Dispatcher.BeginInvoke(new Action(() =>
{
plist.Add(p);
}));
}
});
}
}
[解决办法]
你把ListBox的ItemsPanel换成VirtualStackPanel试试(可能我拼错了),ListBox的默认容器是StackPanel,会把每个item都生成一下,可能会有性能问题
[解决办法]
仔细一看你的代码真绕,又放线程池又Dispatcher的。
你先直接改成
plist = new ObservableCollection<Person>();
这样,不用clear,看看还有没有效率问题。