gpt4 book ai didi

c# - 在 MVVM WPF 中将 DataTable 绑定(bind)到 DataGrid

转载 作者:行者123 更新时间:2023-12-03 10:38:21 25 4
gpt4 key购买 nike

我对整个 C# .net 很陌生,但是我搜索了很多,但找不到如何使它工作。

我的 View 中有一个 DataGrid,如下所示:

<DataGrid Name="SettingGrid" ItemsSource="{Binding Path=PluginSettings, Mode=OneWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="True" Margin="224.4,10,10,10"/>

PluginSettings 是一个 DataTable,根据用户的操作动态填充不同的列和行。
PluginSettings 总是最新的,我已经检查了 Debug模式,列和行总是我想要的。但是 View 永远不会更新。
经过一番谷歌搜索,我发现 DataTable 不可枚举,因此无法绑定(bind)。我将绑定(bind)更改为 {Binding Path=PluginSettings.DefaultView .
这样,我可以使行完美地工作,但列却不行。

当我向我的 DataTable 添加一列时, View 永远不会显示它。
如果我正确理解 DefaultView 是什么,这意味着我无法将用户在 Grid 上所做的更改复制到实际的 DataTable 以保存它们,这实际上是我的目标。

我错过了什么 ?
使用 DataGrid 只是一个糟糕的选择吗,我想做的事情有更好的选择吗?

希望我说清楚了,英语不是我的第一语言。
谢谢

最佳答案

  • 不得不提的是System.Data的使用不鼓励在客户端代码 (WPF) 中使用。
  • 这包括 System.Data.DataSet , System.Data.DataTable ,以及 System.Data 中的任何其他类命名空间。
  • 您应该创建适当的数据模型并改用它。
  • 海事组织,System.Data是服务器端的概念,不应传递给客户端。
  • 例如,在 WinRT 中,它甚至不存在。没有System.Data ,因此,如果您打算将 WPF 应用程序迁移到 WinRT,您将需要重写大量代码。

  • 话虽如此,此示例适用于添加新行和添加新列:
    <Window x:Class="MiscSamples.DataGridAndDataTable"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DataGridAndDataTable" Height="300" Width="300">
    <DockPanel>
    <Button Content="Add Column" DockPanel.Dock="Top" Click="AddColumn"/>
    <Button Content="Add Row" DockPanel.Dock="Top" Click="AddRow"/>
    <DataGrid Name="SettingGrid"
    ItemsSource="{Binding}"
    AutoGenerateColumns="True"/>
    </DockPanel>
    </Window>

    代码背后:
      public partial class DataGridAndDataTable : Window
    {
    public DataTable PluginSettings { get; set; }

    public DataGridAndDataTable()
    {
    InitializeComponent();

    PluginSettings = new DataTable();

    PluginSettings.Columns.Add("Name", typeof (string));
    PluginSettings.Columns.Add("Date", typeof(DateTime));

    PluginSettings.NewRow();
    PluginSettings.NewRow();

    PluginSettings.Rows.Add("Name01", DateTime.Now);

    DataContext = PluginSettings;
    }

    private void AddColumn(object sender, RoutedEventArgs e)
    {
    PluginSettings.Columns.Add("Age", typeof (int));
    DataContext = null;
    DataContext = PluginSettings;
    }

    private void AddRow(object sender, RoutedEventArgs e)
    {
    PluginSettings.Rows.Add("Name01", DateTime.Now);
    }
    }

    关于c# - 在 MVVM WPF 中将 DataTable 绑定(bind)到 DataGrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15775396/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com