WPF将ListBox绑定到数据集

本文关键字:数据集 绑定 ListBox WPF | 更新日期: 2023-09-27 18:06:38

我试图在ListBox中显示一个数据集。以下是我目前得到的:

XAML

<Window x:Class="FilterDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:FilterDemo" 
    Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded_1" >
<Window.Resources>
    <local:FilterDemoBackEndDataSet x:Key="FilterDemoBackEndDataSet"/>
    <CollectionViewSource x:Key="cLIENTSViewSource" Source="{Binding CLIENTS, Source={StaticResource FilterDemoBackEndDataSet}}"/>
</Window.Resources>
<Grid>
    <StackPanel Grid.Column="1" Background="#c4d9f9" >
        <DockPanel HorizontalAlignment="Left" Height="20" Width="220"  Margin="10,5,5,5">
            <TextBox Name="txtSearch" Height="20" Width="160" DockPanel.Dock="Left"  />
            <Button Name="cmdFilter" Height="20" Width="20"  Background="Black" DockPanel.Dock="Right"/>
        </DockPanel>
        <ListBox Name="lstAccountNo"  Height="550"  Width="200" HorizontalAlignment="Left" DisplayMemberPath="AccountNo" ItemsSource="{Binding}"
                             Margin="10,5,5,5" SelectedItem="{Binding AccountNo}" IsSynchronizedWithCurrentItem="True" />
    </StackPanel>
</Grid>

Code behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace FilterDemo
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
      public MainWindow()
      {
          InitializeComponent();
      }
      private void Window_Loaded_1(object sender, RoutedEventArgs e)
      {
          FilterDemo.FilterDemoBackEndDataSet FilterDemoBackEndDataSet = ((FilterDemo.FilterDemoBackEndDataSet)(this.FindResource("FilterDemoBackEndDataSet")));
          // Load data into the table CLIENTS. You can modify this code as needed.
          FilterDemo.FilterDemoBackEndDataSetTableAdapters.CLIENTSTableAdapter FilterDemoBackEndDataSetCLIENTSTableAdapter = new FilterDemo.FilterDemoBackEndDataSetTableAdapters.CLIENTSTableAdapter();
          FilterDemoBackEndDataSetCLIENTSTableAdapter.Fill(FilterDemoBackEndDataSet.CLIENTS);
          System.Windows.Data.CollectionViewSource cLIENTSViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("cLIENTSViewSource")));
          cLIENTSViewSource.View.MoveCurrentToFirst();
      }
  }
}

我有一个名为FilterDemoBackEnd的数据集,一个名为Clients的表和一个名为AccountNo的字段。当我运行上面的代码时,窗口打开了,但没有显示任何项目。

请不要回答一个链接到一个线程,因为我已经搜索了互联网,试图解决这个问题。

XAML很难。

WPF将ListBox绑定到数据集

通过将数据网格拖到主窗口然后删除它来对其进行排序。我不知道这是怎么起作用的,但它确实奏效了。