How to bind a table in a dataset to a WPF datagrid in C# and XAML
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.
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);
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>
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>
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?
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?
Using the Microsoft DataGrid in the following way works for me:
In XAML I include the DataGrid:
<WpfToolkit:DataGrid
Grid.Row="4" Grid.Column="0"
ItemsSource="{Binding Path=GridData, Mode=OneWay}" >
</WpfToolkit:DataGrid>
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;
}
}
精彩评论