可观察的集合不会在linq上更新datagrid

时间:2019-01-31 06:43:22

标签: c# wpf mvvm

我的应用程序中有一个数据网格和文本框。我将在文本框中提供一个数字,然后单击按钮,我希望datagrid从给定的数字中获取数据。数据网格的Itemsource是一个ObservableCollection。问题是当我单击按钮时,数据网格未更新。

我正在学习wpf。我有一个是ObservableCollection的数据网格。通过sql查询填充datagrid的数据。绑定到数据网格工作正常。我在线搜索,发现使用linq我们可以搜索集合并获取数据,但datagrid不会反映任何更改。

ModelClasstab.Where(d => d.claimnumber == "123456712");

在上面,我已经对文本框数据进行了硬编码,以检查条件是否有效

Window.xaml

<Label Width="69" Height="23.277" HorizontalAlignment="Left" Margin="1,-10,30,0" VerticalAlignment="Top" Content="From Date"/>
<TextBox HorizontalAlignment="Left" Width="113" Height="19.277"  Margin="-200,1,-228.962,0"  x:Name="txtboxComments"/>
<Button  Command="{Binding dataSearch}" Margin="300,-20,30,0" Width="60" Height="23.277"  Content="Search"></Button>
<DataGrid x:Name="datagrid" ItemsSource="{Binding ModelClasstab}" AutoGenerateColumns="True" CanUserAddRows="False" Height="350" Width="365" Margin="5" HorizontalAlignment="Left"/>

ViewModel.cs:

   public class ViewModel
  {
    public RelayCommand dataSearch { get; set; }
    public ObservableCollection<tabpageAuditInformationModel> ModelClasstab {get; set;} 


    public ViewModel()
  {   
    FillList();
    dataSearch = new RelayCommand(o => Search());
  }

 public void Search()
    { 
     ModelClasstab.Where(d => d.claimnumber == "123456712");
    }


public void FillList()
    {
        string connectionString = "Data Source=192.168.6.102; Initial Catalog=Operations Productivity Tool;Integrated Security=SSPI;";

        string sql = "SELECT distinct Date_Audited as Date , claimNumber as 
 claimnumber,Audit_id,[Start Time],[End Time],[Total Time] as 
 [Total_time_taken(Mins)] , [Final Status] as finalstatus " +
" FROM dbo.[opcod Audit Information]" +
            //or date = dateadd(day,-1,cast(getdate() as date))) " +"where userName = 'rengar2' ";

        using (var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using (var command = new SqlCommand(sql, connection))
            {

                try
                {


                    adapter = new SqlDataAdapter(command);
                    ds = new DataSet();
                    adapter.Fill(ds, "tblCountries");

                    if (ModelClasstab == null)
                        ModelClasstab = new ObservableCollection<tabpageAuditInformationModel>();

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        var month = Convert.ToDateTime(dr[0]).Month;
                        var year = Convert.ToDateTime(dr[0]).Year;
                        var day = Convert.ToDateTime(dr[0]).Day;


                        ModelClasstab.Add(new tabpageAuditInformationModel
                        {
                            claimnumber = dr[1].ToString(),
                            Date = string.Format("{0}/{1}/{2}", month, day, year),
                            Starttime = dr[3].ToString(),
                            EndTime = dr[4].ToString(),
                            TotalTime = dr[5].ToString()
                        });


                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
    }
     }  

Model.Cs

 public class tabpageAuditInformationModel
  {
   public String Date
   { get; set; }


   public String claimnumber
   { get; set; }

   public String Starttime
   { get; set; }

   public String EndTime
   { get; set; }

   public String TotalTime
   { get; set; }

}

编辑:阅读注释后,我将值分配给了一个变量,并删除了集合中的所有项目,仅将选定的数据添加到列表中。在这里,我无法同时运行两个foreach。断点根本没有进入第二个forloop中。我不确定我的方法。让我知道是否有更好的方法。

         var d1 = ModelClasstab.Where(d => d.claimnumber == "123456712");
                    foreach (var a1 in ModelClasstab.ToList())
                        ModelClasstab.Remove(a1);
                    foreach (var a in d1.ToList())
                        ModelClasstab.Add(new tabpageAuditInformationModel
                        {
                            claimnumber = a.claimnumber,
                            Date = a.Date,
                            Starttime = a.Starttime,
                            EndTime = a.EndTime,
                            TotalTime = a.TotalTime
                        });

                }

1 个答案:

答案 0 :(得分:0)

使用Collection.Where子句,您无需修改​​集合,因此在DataGrid中看不到任何更改。
多种可能性之一是将数据库数据保存在某个变量中,并在Search属性ModelClasstab中进行设置:

public void Search()
{
    ModelClasstab=new ObservableCollection<tabpageAuditInformationModel>(DbData.Where(d => d.claimnumber == "123456712"));
}

通过这种方式,ModelClasstab不必是ObervableCollection,并且(!)您的ViewModel必须实现INotifyPropertyChanged