Ran*_*ter 1 c# data-binding collections wpf performance
我意识到这个问题可以归结为"我的代码为什么这么慢?" 但我希望能从中得到更多.让我解释一下我的代码.
我有一个实现INotifyPropertyChanged的类来进行绑定,该类看起来类似于:
public class Employee : INotifyPropertyChanged
{
string m_strName = "";
string m_strPicturePath = "";
public event PropertyChangedEventHandler PropertyChanged;
public string Picture
{
get { return this.m_strPicturePath; }
set { this.m_strPicturePath = value;
NotifyPropertyChanged("Picture"); }
}
public string Name
{
get { return this.m_strName; }
set { this.m_strName = value;
NotifyPropertyChanged("Name");
}
}
private void NotifyPropertyChanged(String pPropName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(pPropName));
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的XAML中,我创建了一个绑定到该对象的DataTemplate:
<DataTemplate x:Key="EmployeeTemplate">
<Border Height="45" CornerRadius="0" BorderBrush="Gray" BorderThickness="0" Background="Transparent" x:Name="bordItem">
<Grid Width="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Path=Name}" VerticalAlignment="Center" Padding="10" HorizontalAlignment="Stretch" FontWeight="Bold" FontSize="20"/>
<Image Grid.Column="1" Source="{Binding Path=Picture}"></Image>
</Grid>
</Border>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
然后将此模板放在ListBox上:
<ListBox x:Name="lstEmployees" ItemTemplate="{DynamicResource EmployeeTemplate}" VirtualizingStackPanel.VirtualizationMode="Recycling" VirtualizingStackPanel.IsVirtualizing="True"></ListBox>
Run Code Online (Sandbox Code Playgroud)
所以在代码中它被设置为:
lstEmployees.ItemsSource = this.m_Employees;
Run Code Online (Sandbox Code Playgroud)
"m_Employees"列表在应用程序启动时从数据库中获得水分,然后在此之后我设置上面的代码行.ListBox位于TabControl上.
现在,我的实际问题是:我的"m_Employees"列表从数据库中返回了大约500多名员工,因此集合略大.只有当应用程序首次启动并且有人导航到带有ListBox的选项卡时,我才能在WPF中获得性能提升.用户界面冻结大约3秒钟,但只有在应用程序首次启动时才会冻结 - 之后就可以了.
这可能是因为:
任何其他改进上述建议都会受到赞赏.感谢您提前阅读和提供任何建议.
-R.
ItemsSource ="{Binding Empolyess,IsAsync = True }"
您还可以在代码中指定Binding.
希望这可以帮助.