c# - 将数据绑定(bind)/设置源到我的 DataGrid [WPF] 的正确方法是什么

标签 c# mysql wpf xaml datagrid

我是 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/

相关文章:

c# - 如何在 VS 2012 中编辑 .testsettings

mysql - 如何将rails应用程序中的mysql与docker连接?

wpf - 使用 RotateTransform 旋转时如何防止方向改变?

mysql - 在 MySQL 中查找 'free' 次

php - Laravel Eloquent 连接不相关的表?

c# - 为一个组合框而不是另一个组合框设置 ComboBoxItems 的样式?

c# - 使用 WPF 在列表框项目上移动 + 单击功能

具有 Resharper 建议的 C# 静态类

c# - 为什么 FileSystemInfo 不声明 GetAccessControl 方法?

c# - MEF + WPF + MVVM : Where should AggregateCatalog reside?