我有一个 WPF 应用程序,它使用(当前)本地数据库作为绑定源。使用 Visual Studio 2010 工具,我有一个 LINQ-SQL 模型,它充当大多数表单的数据上下文。
我拥有的是一个带有 TextBox 和 Datagrid 的 UserControl。数据网格 ItemSource 是在带有表的 UserControl.Loaded 事件上设置的。TextBox 分配了一个事件,以便在文本更改时在数据库上执行查询,并且在数据网格上更新 ItemSource。
问题在于查询数据库所需的时间。因为我正在为每个搜索重新分配 DataGrid itemsource。
我是否应该在 UserControl 加载时加载所有记录 - 有没有办法在 BackgroundWorker 或类似方法中异步加载记录?
我是否需要在每次搜索后重新分配 DataGrid ItemsSource 或者它们是过滤数据的更有效方式?
谢谢。利亚姆
<UserControl x:Class="Tracker.DocumentsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<DataGrid AutoGenerateColumns="False" Margin="12,34,12,50" Name="dataGrid1">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=ID}" Header="ID" />
<DataGridTextColumn Binding="{Binding Path=Reference}" Header="Reference" />
<DataGridTextColumn Binding="{Binding Path=Subject}" Header="Subject" />
</DataGrid.Columns>
</DataGrid>
<TextBox HorizontalAlignment="Left" Margin="64,8,0,0" Name="txtSearchBox" VerticalAlignment="Top" Width="224" TextChanged="txtSearchBox_TextChanged" />
<TextBlock Text="Search" HorizontalAlignment="Left" Margin="11,12,0,0" Name="label1" VerticalAlignment="Top" Height="23" />
</Grid>
</UserControl>
代码:
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Tracker.Model;
namespace Tracker
{
/// <summary>
/// Interaction logic for DocumentsView.xaml
/// </summary>
public partial class DocumentsView : UserControl
{
private TrackerDataContext db;
public DocumentsView()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(DocumentsView_Loaded);
}
void DocumentsView_Loaded(object sender, RoutedEventArgs e)
{
db = new TrackerDataContext();
dataGrid1.ItemsSource = db.Documents;
}
private void txtSearchBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textbox = sender as TextBox;
if (textbox != null)
{
string searchstr = textbox.Text;
if (!string.IsNullOrEmpty(searchstr))
{
var filtered = from document in db.Documents
where document.Subject.Contains(searchstr)
|| document.Reference.Contains(searchstr)
select document;
dataGrid1.ItemsSource = filtered;
}
else
{
dataGrid1.ItemsSource = db.Documents;
}
}
}
}
}