[英]WPF Databinding: How can I bind a stored procedure to a Listview
我有一个按钮,单击该按钮将在SQL Server上运行存储过程,并在同一窗口的网格中显示结果数据。
在Windows Forms World中,我将创建一个数据表,使用一个数据适配器来填充它,然后将该数据表分配给DataGridView的DataSource属性并保存……这就是我的数据。
我在WPF中使用带有Gridview的ListView尝试了类似的操作,但似乎无法正常工作。 我的XAML中包含以下内容:
<ListView Grid.Row="1" Name="Preview" ItemsSource="{Binding Path=Report}"> <GridView> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=FormalName}" /> </GridView> </ListView>
在我的C#代码中
private void CreateReport(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable("Report");
SqlConnection cn = new SqlConnection("Data Source=DailyTimesheets;
Initial Catalog=DailyTimesheets;Integrated Security=SSPI");
SqlCommand cm = new SqlCommand("Reports.PayrollHoursInterface", cn);
cm.Parameters.AddWithValue("@PayBatchID", 722);
cm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cm);
da.Fill(dt);
Preview.DataContext=dt;
}
当我单击一个按钮(触发CreateReport方法)时,我的数据表被填充并分配给Datacontext,但是什么也没有显示。
我制作了一个示例应用程序,发现您需要用ListView.View包围GridView并将ItemsSource设置为{Binding},如下所示:
<ListView Name="Preview" ItemsSource="{Binding}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=FormalName}" />
</GridView>
</ListView.View>
</ListView>
我认为部分问题是您仍在考虑WinForms。 而不是将网格绑定到表,如何将列表框绑定到集合?
尝试以下方法:
1)创建另一个实现INotifyPropertyChanged的类。 我们将为DataContext使用此类。 将其视为您的BindingEngine。 我通常将其作为Window本身的DataContext,使其在Window中的任何位置都可用。
2)在新类中公开一个ObservableCollection属性,其中YourType是另一个实现INotifyPropertyChanged并公开要显示的数据属性的类。
3)在引擎中创建一个方法来填充您的收藏集。 然后在填充它时触发PropertyChanged事件。
4)将ListBox ItemsSource绑定到属性。
5)创建一个ItemTemplate,并将YourType中的属性名称用于绑定。
这是伪代码,但应该使您接近:
<Window>
<Window.Resources>
<ObjectDataProvider x:Key="MyEngineDS" ObjectType="{x:Type MyEngine:MyEngineNamespace}" d:IsDataSource="True"/>
<DataTemplate x:Key="ItemTemplate1">
<TextBlock Text="{Binding MyPropertyName}" />
</DataTemplate>
</Window.Resources>
<Window.DataContext>
<Binding Mode="OneWay" Source="{StaticResource MyEngineDS}"/>
</Window.DataContext>
<Grid x:Name="LayoutRoot">
<ListBox ItemsSource="MyCollection" ItemTemplate="{DynamicResource ItemTemplate1}" />
</Grid>
</Window>
希望这可以帮助。
尝试改用ItemsSource =“ {Binding}”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.