【问题标题】:Filtering a WPF Datagrid with a Textbox使用文本框过滤 WPF 数据网格
【发布时间】:2015-01-07 02:38:45
【问题描述】:

我正在制作这个应用程序,它使用 XML 节点从 Sharepoint 站点提取数据,

private XmlNode GetListItems(string listTitle)
    {
        var client = new Bluejeanware.MWELS.Lists();
        System.Net.NetworkCredential passCredentials = new System.Net.NetworkCredential("username", "password", "domain");
        client.Credentials = passCredentials;
        return client.GetListItems(listTitle, string.Empty, null, null, string.Empty, null, null);
    }

    public void BindSPDataSource()
    {
        var data = GetListItems("Tasks");
        var result = XElement.Parse(data.OuterXml);
        XNamespace z = "#RowsetSchema";
        var taskItems = from r in result.Descendants(z + "row")
                        select new
                        {
                            TaskName = r.Attribute("ows_LinkTitle").Value,
                            DueDate = r.Attribute("ows_DueDate") != null ? r.Attribute("ows_DueDate").Value : string.Empty,
                            AssignedTo = r.Attribute("ows_AssignedTo") != null ? r.Attribute("ows_AssignedTo").Value : string.Empty,
                        };

        dataGridView.ItemsSource = taskItems;
    }

我想过滤使用文本框提取的数据,这是一个很好的例子,应该是 Stackoverflow 帖子

我很难将此代码转换为一种可以与我的应用程序将数据添加到我的 Datagrid 的方式一起使用的方式,有什么想法吗?

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    以下示例演示了如何:

    • 通过 SharePoint Web Services 从 SharePoint 检索列表数据
    • 绑定到DataGrid并启用过滤

    XAML:

    <Window x:Class="SPO.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Tasks" Width="800px" Height="600px" Name="TasksWindow">
        <StackPanel DataContext="{Binding ElementName=TasksWindow}">
            <TextBox Text="{Binding FilterString, UpdateSourceTrigger=PropertyChanged}" />
            <DataGrid  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding ListItemCollection}" />
        </StackPanel>
    </Window>
    

    后面的代码:

    namespace SPO
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window, INotifyPropertyChanged
        {
            public MainWindow()
            {
                InitializeComponent();
                ListItemCollection = CollectionViewSource.GetDefaultView(LoadTasks());
                ListItemCollection.Filter = FilterTask;
            }
    
    
            public bool FilterTask(object value)
            {
                var entry = value as TaskEntry;
                if (entry != null)
                {
                    if (!string.IsNullOrEmpty(_filterString))
                    {
                        return entry.TaskName.Contains(_filterString);
                    }
                    return true;
                }
                return false;
            }
    
            /// <summary>
            /// Bind SP Data Source 
            /// </summary>
            private IEnumerable<TaskEntry> LoadTasks()
            {
                var data = GetListItems("http://intranet.contoso.com","Tasks");
                var result = XElement.Parse(data.OuterXml);
                XNamespace z = "#RowsetSchema";
                var taskItems = from r in result.Descendants(z + "row")
                                select new TaskEntry
                                    {
                                        TaskName = r.Attribute("ows_LinkTitle").Value,
                                        DueDate = r.Attribute("ows_DueDate") != null ? r.Attribute("ows_DueDate").Value : string.Empty,
                                        AssignedTo = r.Attribute("ows_AssignedTo") != null ? r.Attribute("ows_AssignedTo").Value : string.Empty,
                                    };
                return taskItems;
             }
    
    
            private XmlNode GetListItems(string webUri,string listTitle)
            {
                var client = new Lists.Lists();
                client.Url = webUri + "/_vti_bin/Lists.asmx";
                return client.GetListItems(listTitle, string.Empty, null, null, string.Empty, null, null);
            }
    
    
    
            public ICollectionView ListItemCollection
            {
                get { return _listItemCollection; }
                set { _listItemCollection = value; NotifyPropertyChanged("ListItemCollection"); }
            }
    
    
    
    
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged(string property)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(property));
                }
            }
    
            public string FilterString
            {
                get { return _filterString; }
                set
                {
                    _filterString = value;
                    NotifyPropertyChanged("FilterString");
                    if (_listItemCollection != null)
                    {
                        _listItemCollection.Refresh();
                    }
                }
            }
    
    
            private ICollectionView _listItemCollection;
            private string _filterString;
    
        }
    
        public class TaskEntry
        {
            public string TaskName { get; set; }
            public string DueDate { get; set; }
            public string AssignedTo { get; set; }
        }
    }
    

    结果

    【讨论】:

      【解决方案2】:

      -首先定义一个TaskItem类来保存OuterXml中每个节点的属性。

      -确保您的ViewModel(或您的代码隐藏,如果设置了DataContext)实现INorifyPropertyChanged 接口以将属性中的更改传播到UI)。

      -然后将您的taskItems 转换为TaskItem 类的ObservableCollection 属性,并定义与过滤器TextBox 绑定的过滤器属性。

      这里是完整代码

         public partial class MainWindow : Window, INotifyPropertyChanged
      {
          public MainWindow()
          {
              InitializeComponent();
              //Populate the TaskItems collection using BindSPDataSource() method
      
          }
          private String _filter = String.Empty;
          public String Filter
          {
              get
              {
                  return _filter;
              }
      
              set
              {
                  if (_filter == value)
                  {
                      return;
                  }
      
                  _filter = value;
                  OnPropertyChanged();
                  TaskItems = new ObservableCollection<TaskItem>(TaskItems.Where(x => x.AssignedTo.ToLower().Contains(_filter) ||
                      x.DueDate.ToLower().Contains(_filter) ||
                      x.TaskName.ToLower().Contains(_filter)
                      ));
              }
          }
      
          private ObservableCollection<TaskItem> _taskItem;
          public ObservableCollection<TaskItem> TaskItems
          {
              get
              {
                  return _taskItem;
              }
      
              set
              {
                  if (_taskItem == value)
                  {
                      return;
                  }
      
                  _taskItem = value;
                  OnPropertyChanged();
              }
          }
      
      
          public event PropertyChangedEventHandler PropertyChanged;
      
          [NotifyPropertyChangedInvocator]
          protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
          {
              PropertyChangedEventHandler handler = PropertyChanged;
              if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
          }
      }
      public class TaskItem
      {
          public String TaskName { get; set; }
          public String DueDate { get; set; }
          public String AssignedTo { get; set; }
      }
      

      和 Xaml:

       <StackPanel>
          <TextBox Text="{Binding Filter,Mode=TwoWay}" HorizontalAlignment="Stretch"/>
          <DataGrid ItemsSource="{Binding TaskItems}" AutoGenerateColumns="True">
      
          </DataGrid>
      </StackPanel>
      

      别忘了设置DataContext:

      DataContext="{Binding RelativeSource={RelativeSource Self}}"
      

      最后在构造函数中不要直接填充DataGridItemSource,在BindSPDataSource()方法中修改这个: dataGridView.ItemsSource = taskItems; 像这样:

       TaskItems=new ObservableCollection(taskItems);
      

      【讨论】:

        猜你喜欢
        • 2017-12-10
        • 2016-01-20
        • 1970-01-01
        • 2011-06-28
        • 2012-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-02
        相关资源
        最近更新 更多