如何在 C# 和 XAML 中将数据集中的表绑定到 WPF 数据网格 [英] How to bind a table in a dataset to a WPF datagrid in C# and XAML

查看:21
本文介绍了如何在 C# 和 XAML 中将数据集中的表绑定到 WPF 数据网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一些非常简单的东西:将 WPF 数据网格绑定到数据表,以便在设计时查看列.我无法让任何示例对我有用.

I have been searching to hours for something very simple: bind a WPF datagrid to a datatable in order to see the columns at design-time. I can’t get any of the examples to work for me.

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

Here is the C# code to populate the datatable InfoWork inside the dataset info:

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

问题是无论我如何声明‘info’或‘infoWork’Visual Studio/XAML都找不到.我试过了:

The problem is no matter how I declare ‘info’ or ‘infoWork’ Visual Studio/XAML can’t find it. I have tried:

<Window.Resources>
    <ObjectDataProvider x:Key="infoWork" ObjectType="{x:Type local:info}"  />
</Window.Resources>

我也尝试过 wpf.codeplex 中的这个示例,但 XAML 甚至不喜欢local:"关键字!

I have also tried this example from wpf.codeplex, but XAML doesn’t even like the "local:" keyword!

<Window.Resources>
   <local:info x:Key="infoWork"/>
</Window.Resources>

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

There are really two main questions here: 1) How do I declare the table InfoWork in C# so that XAML can see it? I tried declaring it Public in the window class that XAML exists in with no success. 2) How do I declare the windows resource in XAML, specifcally the datatable inside the dataset?

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

Out of curiosity, is there a reason that ItemsSource just doesn't show up as a property that be set in the properties design window?

推荐答案

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

Using the Microsoft DataGrid in the following way works for me:

在 XAML 中,我包含了 DataGrid:

In XAML I include the DataGrid:

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

在我的视图模型中,我公开了一个 DataView:

In my view model I expose a 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# 和 XAML 中将数据集中的表绑定到 WPF 数据网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆