c# - 如何将数据集中的表绑定(bind)到 C# 和 XAML 中的 WPF 数据网格

标签 c# wpf datagrid

我一直在寻找一些非常简单的东西:将 WPF 数据网格绑定(bind)到数据表,以便在设计时查看列。我找不到任何适合我的例子。

这是在数据集信息中填充数据表 InfoWork 的 C# 代码:

info = new Info();
InfoTableAdapters.InfoWorkTableAdapter adapter = new InfoTableAdapters.InfoWorkTableAdapter();
adapter.Fill(info.InfoWork);

问题是无论我如何声明“info”或“infoWork”,Visual Studio/XAML 都找不到它。我努力了:
<Window.Resources>
    <ObjectDataProvider x:Key="infoWork" ObjectType="{x:Type local:info}"  />
</Window.Resources>

我也尝试过 wpf.codeplex 中的这个示例,但 XAML 甚至不喜欢“local:”关键字!
<Window.Resources>
   <local:info x:Key="infoWork"/>
</Window.Resources>

这里实际上有两个主要问题:
1) 如何在 C# 中声明表 InfoWork 以便 XAML 可以看到它?我尝试在 XAML 所在的窗口类中将其声明为 Public,但没有成功。
2) 如何在 XAML 中声明 windows 资源,特别是数据集中的数据表?

出于好奇,是否存在 ItemsSource 没有显示为在属性设计窗口中设置的属性的原因?

最佳答案

以下列方式使用 Microsoft DataGrid 对我有用:

在 XAML 中,我包括 DataGrid:

    <WpfToolkit:DataGrid
        Grid.Row="4" Grid.Column="0"
        ItemsSource="{Binding Path=GridData, Mode=OneWay}" >
    </WpfToolkit:DataGrid>

在我的 View 模型中,我公开了一个 DataView:
  public DataView GridData
  {
     get
     {
        DataSet ds = new DataSet("MyDataSet");

        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
           SqlCommand cmd = conn.CreateCommand();
           cmd.CommandType = CommandType.Text;
           cmd.CommandText = "SELECT * FROM HumanResources.Employee";

           SqlDataAdapter da = new SqlDataAdapter(cmd);
           da.Fill(ds);
        }

        return ds.Tables[0].DefaultView;
     }
  }

关于c# - 如何将数据集中的表绑定(bind)到 C# 和 XAML 中的 WPF 数据网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2511177/

相关文章:

c# - 如果你改变它们的身份,HashSets 不会保持元素的唯一性

c# - 在发布期间包含文件

c# - WPF 列表框 DisplayMemberPath 和 SelectedValuePath

WPF:如何在运行时双击更改按钮内容(文本)

c# - 动态工具提示取决于鼠标悬停在数据网格中的一行上(不是数据 GridView )

WPF 工具包 DataGrid 复选框问题

wpf - 我需要对RowDetailsTemplate进行扩展/折叠

c# - ASP.NET MVC 局部 View 中 Ajax 形式的文件上传不起作用

c# - 从 int 获取枚举值

c# - 命令执行期间遇到 fatal error mysql c#