我一直在寻找一些非常简单的东西:将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中声明windows资源,特别是数据集中的数据表?
出于好奇,有没有理由认为ItemsSource不会显示为在属性设计窗口中设置的属性?
答案 0 :(得分:5)
以下列方式使用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;
}
}