簡體   English   中英

如何將數據集中的表綁定到C#和XAML中的WPF數據網格

[英]How to bind a table in a dataset to a WPF datagrid in C# and XAML

我一直在尋找一些非常簡單的東西:將WPF數據網格綁定到數據表,以便在設計時查看列。 我無法讓任何一個例子適合我。

以下是在數據集信息中填充數據表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中聲明窗口資源,特別是數據集中的數據表?

出於好奇,有沒有理由說ItemsSource不會顯示為在屬性設計窗口中設置的屬性?

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

在XAML中我包含DataGrid:

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

在我的視圖模型中,我公開了一個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;
     }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM