我是 wpf 的初学者,所以请耐心等待:)
我在 MySql 数据库中存储了 40.000 篇文章,当我单击按钮时,我将打开一个加载这些文章的窗口,我是这样做的:
/// <summary>
/// Interaction logic
/// </summary>
public partial class ArticlesAdd : Window
{
public ObservableCollection<MyArticles> articlesList = ObservableCollection<MyArticles>(ArticlesController.SelectAll());
public ArticlesAdd()
{
this.InitializeComponent();
// Setting source to my DATAGRID when this window is loaded/opened
dataGridMyArticles.ItemsSource = articlesList;
}
}
但我看到一些示例直接在 DataGrid 控件上设置 ItemsSource,如下所示(在 XAML 部分):
<DataGrid Name="dataGridMyArticles" ItemsSource="{Binding Source=articlesList}" AutoGenerateColumns="False">
但我不知道这是如何工作的以及应该如何实现,因为我正在使用 dataGridMyArticles.ItemsSource =articleList;
XAML 端的 ItemsSource="{Binding Source=articlesList}"
是否比绑定(bind)背后的代码更快?
IsAsync=True
会使数据绑定(bind)更快/打开窗口更快或类似的事情吗?
那么,如何在不使用后台代码的情况下将该列表绑定(bind)到我的 DataGrid
,这种方法比在我的 Class 中设置
构造函数..?DataGrid
源更快
谢谢大家 干杯
最佳答案
当您遵循模型- View - View 模型 (MVVM) 设计模式时,将 View 中的元素绑定(bind)到 View 模型的源属性是常见做法。 MVVM 与性能无关,但它是开发基于 XAML 的 UI 应用程序时推荐使用的设计模式。
它不会使您的应用程序变得更快,但如果您做得正确,它将使应用程序更易于维护、测试和开发。您可以在 MSDN 上阅读有关使用 MVVM 模式实现应用程序的动机的更多信息:https://msdn.microsoft.com/en-us/library/hh848246.aspx 。如果您使用 Google 或 Bing,还有更多在线资源可供使用。
在您的特定示例中,您将定义一个包含文章列表的 View 模型类:
public class ArticlesViewModel
{
public ObservableCollection<MyArticles> ArticlesList { get; private set; }
public ArticlesViewModel()
{
ArticlesList = ObservableCollection<MyArticles>(ArticlesController.SelectAll());
}
}
将 View 的DataContext
设置为此类的实例:
public partial class ArticlesAdd : Window
{
public ArticlesAdd()
{
this.InitializeComponent();
DataContext = new ArticlesViewModel();
}
}
然后,您可以绑定(bind)到 DataContext
/view 模型的任何公共(public)属性:
<DataGrid Name="dataGridMyArticles" ItemsSource="{Binding Source=ArticlesList}" AutoGenerateColumns="False">
您可能还想在后台调用 ArticlesController.SelectAll()
方法,以防止 UI 在从数据库收集数据期间卡住,但这是另一个问题与 MVVM 和绑定(bind)的使用没有直接关系的故事。
关于c# - 将数据绑定(bind)/设置源到我的 DataGrid [WPF] 的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48613994/