wpf 将DataGrid绑定到DataTable时没有行或列

cotxawn7  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(217)

我试图在DataGrid中显示SQL Server表的内容。我已经将其减少到最基本的版本,并保留所有默认值,并且看不到任何列标题或任何行。
下面是我的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Test1DataSet test1DataSet = new Test1DataSet();
        Test1DataSetTableAdapters.AdminUserTableAdapter tableAdapter =
            new Test1DataSetTableAdapters.AdminUserTableAdapter();
        tableAdapter.Fill(test1DataSet.AdminUser);

       Test1DataSet.AdminUserDataTable dataTable = tableAdapter.GetData();
        Console.WriteLine(dataTable.Count);

        dataGrid.DataContext = dataTable.DefaultView;
    }
}

下面是XAML:

<Grid Name="Grid1">
    <DataGrid Margin="25" Name="dataGrid">
      <!--  <DataGrid.Columns>
            <DataGridTextColumn Header="id" Binding="{Binding id}" />
            <DataGridTextColumn Header="Name" Binding="{Binding LastName}" />
        </DataGrid.Columns> -->
    </DataGrid>
</Grid>

表格定义:CREATE TABLE [dbo].[AdminUser]([id] INT IDENTITY(1,1)NOT NULL,[EmployeeNumber] NVARCHAR(30)NOT NULL,[FirstName] NVARCHAR(100)NULL,[LastName] NVARCHAR(100)NULL,[isSA] BIT NOT NULL,[isDA] BIT NOT NULL);

sqougxex

sqougxex1#

FramworkElement.DataContext属性是用来作为数据绑定的上下文的。它允许定义与源无关的绑定,当数据源更改时可以重用这些绑定。
Data binding overview (WPF .NET)
当你想在ItemsControl中显示数据时,你必须始终将数据源分配给ItemsControl.ItemsSource属性(而不是FrameworkElement.DataContext)。
使用数据绑定(和DataContext)分配数据源:

class MainWindow : Window
{
  public DataTable TableData { get; }

  public MainWindow()
  {
    // Set DataContext for data binding,
    // where this MainWindow instance will implicitly serve as the data source.
    this.DataContext = this
  }
}
<Window>
  
  <!-- DataGrid inherits the DataContext of its parent (MainWindow) implicitly -->
  <DataGrid ItemsSource="{Binding TableData}" />
</Window>

或者如果您不使用数据绑定:

myDataGrid.ItemsSource = this.TableData.DefaultView;

相关问题