WPF ItemsSource Order by Getter

public ObservableCollection<CustomerModel> CustomerCollection
{
get
{
if(customerCollection!=null)
{
var thirdList = customerCollection.ToList().OrderBy(x => x.RowGuid).ToList();
customerCollection.Clear();
foreach(var cus in thirdList)
{
customerCollection.Add(cus);
}
}
return customerCollection;
}
set
{
customerCollection = value;
OnPropertyChanged("CustomerCollection");
}
}

private ICommand loadCmd;
public ICommand LoadCmd
{
get
{
if(loadCmd==null)
{
loadCmd = new DelegateCommand<string>((obj) =>
{
FillDG();
});
}
return loadCmd;
}
}

private void FillDG()
{
List<CustomerModel> customerList = new List<CustomerModel>();
string source = ConfigurationSettings.AppSettings["SqlSource"];
SqlConnection conn = new SqlConnection(source);
conn.Open();
if(conn.State==ConnectionState.Open)
{
string sql = " select name,ProductNumber,rowguid from Production.Product";
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
sda.Fill(ds);
if(ds.Tables[0].Rows.Count>0)
{
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
customerList.Add(new CustomerModel()
{
Name = ds.Tables[0].Rows[i][0].ToString(),
ProductName = ds.Tables[0].Rows[i][1].ToString(),
RowGuid = ds.Tables[0].Rows[i][2].ToString()
});
}
}
}

CustomerCollection = new ObservableCollection<CustomerModel>(customerList);
}

原文地址:https://www.cnblogs.com/Fred1987/p/6238531.html