代码之家  ›  专栏  ›  技术社区  ›  Rob

WPF数据绑定:如何将存储过程绑定到ListView

  •  2
  • Rob  · 技术社区  · 15 年前

    我有一个按钮,单击该按钮将在SQL服务器上运行一个存储过程,并在同一窗口的网格中显示结果数据。

    在Windows窗体世界中,我将创建一个数据表,使用一个数据适配器填充它,然后将该数据表分配给我的DataGridView和Poof的DataSource属性…这是我的数据。

    我在WPF中尝试过类似的方法,使用带有网格视图的ListView,但似乎无法使其工作。我的XAML中包含以下内容:

    <ListView Grid.Row="1" Name="Preview" ItemsSource="{Binding Path=Report}">
      <GridView>
        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=FormalName}" />
      </GridView>
    </ListView>
    

    在我的密码里

    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,但不会显示任何内容。

    3 回复  |  直到 12 年前
        1
  •  6
  •   statenjason    15 年前

    我制作了一个示例应用程序,发现您需要用listview.view包围您的gridview.view并将itemssource设置为binding,如下所示:

    <ListView Name="Preview" ItemsSource="{Binding}">
    <ListView.View>
      <GridView>
        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=FormalName}" />
      </GridView>
     </ListView.View>
    </ListView>
    
        2
  •  1
  •   Joel Cochran    15 年前

    我认为问题的一部分在于你还在考虑WinForms。与其将网格绑定到表,不如将列表框绑定到集合?

    试试这个:

    1)创建另一个实现inotifyPropertyChanged的类。我们将对DataContext使用这个类。把它当作你的绑定引擎。我通常将其作为窗口本身的数据上下文,使其在窗口中的任何位置都可用。

    2)在新类中公开属于ObservableCollection的属性,其中,您的类型是另一个实现InotifyPropertyChanged的类,并公开您希望显示的数据属性。

    3)在引擎中创建一个填充集合的方法。然后在填充时激发PropertyChanged事件。

    4)将列表框项源绑定到属性。

    5)创建一个itemTemplate,并使用您的类型中的属性名进行绑定。

    这是psuedo代码,但应该可以关闭:

    <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>
    

    希望这有帮助。

        3
  •  0
  •   mdm20    15 年前

    尝试改用itemssource=“binding”。