/*沒有在xaml設置上下文window.context是因為 命名空間一直對應不上 所以在xaml.cs
里面綁定*/
<Window x:Class="DataGrid.views.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:DataGrid"xmlns:AutoGrid="clr-namespace:WpfAutoGrid"xmlns:viewmodels="clr-namespace:DataGrid.viewmodels"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid><AutoGrid:AutoGrid ColumnCount="2" RowCount="2" Rows="5*,*" Columns="*,*" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"><DataGrid Grid.ColumnSpan="2" ItemsSource="{Binding Itemsview}"></DataGrid><TextBox HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Text="{Binding Pagenum}" ></TextBox><Button HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Command="{Binding NextPageCommand}">Next</Button></AutoGrid:AutoGrid></Grid>
</Window>
using Bogus;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Data;
using Bogus;
using System.Collections.ObjectModel;namespace DataGrid.viewmodels
{public class student //類變量要是屬性getset{public int Id { get; set; }public string Name { get; set; }public double Score { get; set; }}public class StudentDataGenerator{public static ObservableCollection<student> GenerateStudents(int count){var fakeStudents = new Faker<student>().RuleFor(s => s.Id, f => f.IndexGlobal + 1) // ID從1開始.RuleFor(s => s.Name, f => f.Name.FullName()) // 隨機姓名.RuleFor(s => s.Score, f => f.Random.Double(0, 100)) // 0-100的隨機分數.Generate(count); // 生成指定數量的學生return new ObservableCollection<student>(fakeStudents);}} /*bogus生成數據*/public partial class DataControl:ObservableObject /*這里一定要partial*/{private CollectionView _itemsview;private const int _pagesize = 10;private int _pagenum = 1;public CollectionView Itemsview { get { return _itemsview; } }public int Pagenum{get { return _pagenum; }set { SetProperty(ref _pagenum, value); Itemsview?.Refresh(); }}public int TotalPages => (int)Math.Ceiling(Students.Count / (double)_pagesize);[ObservableProperty]ObservableCollection<student> _students;[RelayCommand]public void NextPage(){if (_pagenum < TotalPages) // 如果還有下一頁{Pagenum++; //這里一定只能改屬性 }}[RelayCommand] //relaycommand生成的命令會在函數后面加上commandpublic void PrevPage(){if (_pagenum > 1) // 如果不是第1頁{Pagenum--;}}//原理就是_itemsview匹配數據 過濾之后留下頁碼是1的內容 返回true的內容會被存入_itemsviewpublic DataControl(ObservableCollection<student> stus) //有參構造函數傳數據{this._students = stus; //這里要用observablecollection 不能用enumerable_itemsview = (CollectionView)CollectionViewSource.GetDefaultView(this._students);_itemsview.Filter = (item) =>{var index = Students.IndexOf((student)item); int itemPage = (index / _pagesize) + 1;return itemPage == Pagenum; // 只顯示當前頁的數據;};}}}
using System.Text;
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;
using DataGrid.viewmodels;namespace DataGrid.views
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();this.DataContext = new DataControl(StudentDataGenerator.GenerateStudents(36));}}
}//xaml不好綁定viewmodel 就只能到cs里面綁定了 this.datacontext = new ........
//壞處就是xaml不會有提示
sqlsugar操作
using SqlSugar;
using System;public static class IntDbHelper
{private static SqlSugarScope Connection => new SqlSugarScope(new ConnectionConfig(){ConnectionString = "Data Source=./data.db",DbType = DbType.Sqlite,IsAutoCloseConnection = true});// -------------------- 針對int值的操作 --------------------// 插入數據(返回新增的ID)public static int Insert(string tableName, Dictionary<string, object> values){return Connection.Insertable(values).AS(tableName).ExecuteReturnIdentity();}// 查詢數據(返回單個int值)public static int GetInt(string tableName, string field, int id){return Connection.Queryable<dynamic>().AS(tableName).Where($"Id = {id}").Select(field).First();}// 更新數據(更新指定int字段)public static bool UpdateInt(string tableName, int id, string field, int newValue){return Connection.Updateable<dynamic>().AS(tableName).SetColumns($"{field} = {newValue}").Where($"Id = {id}").ExecuteCommand() > 0;}// 刪除數據(根據int ID)public static bool Delete(string tableName, int id){return Connection.Deleteable<dynamic>().AS(tableName).Where($"Id = {id}").ExecuteCommand() > 0;}
}
?int step = 0;
var result = from person in people
? ? ? ? ? ? ?let currentId = step
? ? ? ? ? ? ?select new
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?Id = (step += 2) - 2, // 0, 2, 4...
? ? ? ? ? ? ? ? ?Person = person
? ? ? ? ? ? ?};
不用直接操作id? 可以linq給序號??
?
?
linq里面只能OfType<student>() 不能強轉
datagrid 返回的 selecteditems 是IList類型的
?
CollectionView 方式
- 優點:自動處理分頁,刪除后自動回填
- 缺點:需要調用?Refresh()?刷新視圖
會自動回填
?
linq加反射則不會自動回填
Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "Apple"; // 鍵 1 不存在,自動添加鍵值對 {1: "Apple"}
dict[2] = "Banana"; // 鍵 2 不存在,自動添加鍵值對 {2: "Banana"}
dict[1] = "Avocado"; // 鍵 1 已存在,直接覆蓋值,變成 {1: "Avocado"}
List<int> keyList = dict.Keys.ToList(); // 轉為 List<int>
int[] keyArray = dict.Keys.ToArray(); // 轉為 int[]
var longNameStudents = from s in students
? ? ? ? ? ? ? ? ? ? ? let nameLength = s.Name.Length // 定義臨時變量
? ? ? ? ? ? ? ? ? ? ? where nameLength > 5 // 復用計算結果
? ? ? ? ? ? ? ? ? ? ? select new { s.Name, nameLength };