增加DataGridEx

This commit is contained in:
chfei committed 2026-10-28 16:48:02 +08:00
1 parent 497e9f1c34
commit 499379e20b
23 files changed
+2682 -6

No files matched your search

@@ -0,0 +1,354 @@
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Threading;
using Store.Management.Framework.Controls;
using Store.Management.ViewModels;
using Store.Management.Views;
internal static class Program
{
[STAThread]
private static int Main()
{
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
Application app = new() { ShutdownMode = ShutdownMode.OnExplicitShutdown };
foreach (string source in new[]
{
"/Store.Management.Framework;component/Resources/HandyControlBasic.xaml",
"/HandyControl;component/Themes/SkinDefault.xaml",
"/HandyControl;component/Themes/Theme.xaml",
"/Store.Management.Framework;component/Resources/FrameworkTheme.xaml"
})
{
app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri(source, UriKind.Relative) });
}
BindingErrors errors = new();
PresentationTraceSources.DataBindingSource.Listeners.Add(errors);
Window? window = null;
try
{
app.Resources["DialogWindowStyle"] = new Style(typeof(Window));
DataGridTestView dialogView = new();
DataGridTestViewModel dialogVm = (DataGridTestViewModel)dialogView.DataContext;
Store.Management.Framework.Controls.DialogWindow dialog = new()
{
Content = dialogView, DataContext = dialogVm,
Left = -10000, Top = -10000, ShowInTaskbar = false
};
Check(dialog.Width == 1360 && dialog.Height == 800 && dialog.ResizeMode == ResizeMode.CanResizeWithGrip, "dialog size and resizing");
Check(dialogVm.CanCloseDialog() && !dialogVm.AllowEnter && dialogVm.AllowEscape, "dialog keyboard behavior");
bool closeRequested = false;
dialogVm.RequestClose += _ => closeRequested = true;
dialogVm.CancelCommand.Execute(null);
Check(closeRequested, "dialog cancellation requests close");
dialog.Close();
DataGridTestView view = new();
DataGridTestViewModel vm = (DataGridTestViewModel)view.DataContext;
DataGridEx grid = (DataGridEx)view.FindName("StoreGrid");
window = new Window { Content = view, Width = 1280, Height = 760, Left = -10000, Top = -10000, ShowInTaskbar = false };
window.Show();
Pump();
Check(grid.BorderThickness.Left == 1 && grid.BorderThickness.Right == 1, "continuous table side borders");
Check(vm.TotalCount == 237 && grid.Items.Count == 50 && grid.PageCount == 5, "Bogus data and page count");
Check(grid.Columns.Count == 10 && Equals(grid.Columns[0].Header, "序号"), "separate serial column");
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(0);
Check(DataGridEx.GetRowNumber(row) == 1, "first row number");
Check(Descendants<TextBlock>(row).Any(text => text.Text == "1"), "row number binding inherits into cell");
Check(Descendants<CheckBox>(row).Any(), "row checkbox rendered independently");
Check(Descendants<CheckBox>(grid).Any(box => System.Windows.Automation.AutomationProperties.GetName(box) == "全选行"), "header checkbox rendered");
CheckBox selectAll = Descendants<CheckBox>(grid).Single(box => System.Windows.Automation.AutomationProperties.GetName(box) == "全选行");
CheckBox selectRow = Descendants<CheckBox>(row).Single();
Check(ReferenceEquals(selectAll.Template, selectRow.Template), "header and row checkbox share the theme template");
double headerCenter = selectAll.TranslatePoint(new Point(selectAll.ActualWidth / 2, 0), grid).X;
double rowCenter = selectRow.TranslatePoint(new Point(selectRow.ActualWidth / 2, 0), grid).X;
Check(Math.Abs(headerCenter - rowCenter) <= 1, "header and row checkbox centers align");
DataGridColumnHeader nameHeader = Descendants<DataGridColumnHeader>(grid).Single(header => Equals(header.Content, "店铺名称"));
grid.Columns[1].SortDirection = ListSortDirection.Ascending;
Pump();
FrameworkElement sortArrow = (FrameworkElement)nameHeader.Template.FindName("SortArrowGrid", nameHeader);
Check(sortArrow != null && sortArrow.IsVisible, "flat custom header and sort arrow template applied");
double arrowRight = sortArrow.TranslatePoint(new Point(sortArrow.ActualWidth, 0), nameHeader).X;
Check(Math.Abs(nameHeader.ActualWidth - arrowRight - nameHeader.Padding.Right) <= 1, "sort arrow stays at the far right");
grid.Columns[1].SortDirection = null;
ScrollViewer viewer = (ScrollViewer)grid.Template.FindName("DG_ScrollViewer", grid);
ScrollBar horizontalBar = (ScrollBar)viewer.Template.FindName("PART_HorizontalScrollBar", viewer);
Check(Math.Abs(horizontalBar.TranslatePoint(new Point(), viewer).X) <= 1, "horizontal scrollbar starts at the left edge");
Check(grid.SelectionUnit == DataGridSelectionUnit.CellOrRowHeader, "demo uses cell or row header selection");
DataGridCell businessCell = Descendants<DataGridCell>(row).First(cell => cell.Column == grid.Columns[1]);
businessCell.RaiseEvent(new System.Windows.Input.MouseButtonEventArgs(System.Windows.Input.Mouse.PrimaryDevice, Environment.TickCount, System.Windows.Input.MouseButton.Left)
{
RoutedEvent = System.Windows.Input.Mouse.MouseDownEvent
});
Pump();
Check(businessCell.IsSelected && !row.IsSelected && vm.SelectedStores.Count == 0, "business cell selects only a cell");
Check(ReferenceEquals(businessCell.Background, grid.SelectedRowBackground), "selected cell has visible highlight");
Border cellBackground = Descendants<Border>(businessCell).First();
Check(ReferenceEquals(cellBackground.Background, grid.SelectedRowBackground), "cell template renders selected background");
grid.SelectedCells.Clear();
Pump();
Check(!businessCell.IsSelected &&
businessCell.Background is SolidColorBrush previousBrush && previousBrush.Color.A == 0,
"clearing cell selection removes highlight");
DataGridCell numberCell = Descendants<DataGridCell>(row).First(cell => cell.Column == grid.Columns[0]);
numberCell.RaiseEvent(new System.Windows.Input.MouseButtonEventArgs(System.Windows.Input.Mouse.PrimaryDevice, Environment.TickCount, System.Windows.Input.MouseButton.Left)
{
RoutedEvent = System.Windows.Input.Mouse.PreviewMouseDownEvent
});
Pump();
Check(row.IsSelected && vm.SelectedStores.Count == 1, "serial cell selects whole row");
vm.SelectedStores.Clear();
DataGridRowHeader rowHeader = (DataGridRowHeader)row.Template.FindName("PART_RowHeader", row);
rowHeader.RaiseEvent(new System.Windows.Input.MouseButtonEventArgs(System.Windows.Input.Mouse.PrimaryDevice, Environment.TickCount, System.Windows.Input.MouseButton.Left)
{
RoutedEvent = System.Windows.Input.Mouse.PreviewMouseDownEvent
});
Check(row.IsSelected && vm.SelectedStores.Count == 1, "checkbox header selects row in mixed mode");
vm.SelectedStores.Clear();
DataGridLength[] columnWidths = grid.Columns.Select(column => column.Width).ToArray();
foreach (DataGridColumn column in grid.Columns) { column.Width = 100; }
window.Width = 1800;
Pump();
Point blankPoint = new(row.ActualWidth - 10, row.ActualHeight / 2);
UIElement blankTarget = (UIElement)row.InputHitTest(blankPoint);
Check(blankTarget != null, "row trailing space is hit-testable");
blankTarget.RaiseEvent(new System.Windows.Input.MouseButtonEventArgs(System.Windows.Input.Mouse.PrimaryDevice, Environment.TickCount, System.Windows.Input.MouseButton.Left)
{
RoutedEvent = System.Windows.Input.Mouse.PreviewMouseDownEvent
});
Pump();
Check(row.IsSelected && vm.SelectedStores.Contains((DemoStore)row.Item), "click trailing row space selects row");
vm.SelectedStores.Clear();
grid.ShowCheckBox = false;
Pump();
blankTarget = (UIElement)row.InputHitTest(new Point(row.ActualWidth - 10, row.ActualHeight / 2));
blankTarget.RaiseEvent(new System.Windows.Input.MouseButtonEventArgs(System.Windows.Input.Mouse.PrimaryDevice, Environment.TickCount, System.Windows.Input.MouseButton.Left)
{
RoutedEvent = System.Windows.Input.Mouse.PreviewMouseDownEvent
});
Check(row.IsSelected, "trailing space selection works with hidden row checkbox");
vm.SelectedStores.Clear();
grid.ShowCheckBox = true;
for (int index = 0; index < grid.Columns.Count; index++) { grid.Columns[index].Width = columnWidths[index]; }
window.Width = 1280;
Pump();
DataGridEx.ToggleSelectAllCommand.Execute(null, grid);
Check(vm.SelectedStores.Count == 50 && grid.AreAllRowsSelected == true, "select all publishes to VM");
vm.SelectedStores.RemoveAt(0);
Check(grid.SelectedItems.Count == 49 && grid.AreAllRowsSelected == null, "partial selection from VM");
vm.SelectedStores.Clear();
Check(grid.AreAllRowsSelected == false && grid.SelectionSummary == "选择记录后可批量操作", "clear selection");
DataGridEx.NextPageCommand.Execute(null, grid);
Pump();
Check(grid.PageIndex == 2 && grid.Items.Count == 50 && vm.SelectedStores.Count == 0, "next page and clear selection");
row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(0);
Check(DataGridEx.GetRowNumber(row) == 51, "page offset for row number");
grid.Items.SortDescriptions.Add(new SortDescription(nameof(DemoStore.Name), ListSortDirection.Descending));
Pump();
row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(0);
Check(DataGridEx.GetRowNumber(row) == 51, "sorting recomputes display positions");
grid.ScrollIntoView(grid.Items[49]);
Pump();
row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(49);
Check(DataGridEx.GetRowNumber(row) == 100, "recycled row number");
grid.ScrollIntoView(grid.Items[0]);
Pump();
DataGridEx.LastPageCommand.Execute(null, grid);
Pump();
Check(grid.PageIndex == 5 && grid.Items.Count == 37 && !DataGridEx.NextPageCommand.CanExecute(null, grid), "last page boundary");
grid.PageSize = 20;
Pump();
Check(grid.PageIndex == 1 && grid.PageCount == 12 && grid.Items.Count == 20, "page size resets to first page");
Button columns = (Button)grid.Template.FindName("PART_ColumnsButton", grid);
columns.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
Pump();
MenuItem[] options = columns.ContextMenu.Items.OfType<MenuItem>().Where(item => item.IsCheckable).ToArray();
Check(options.Length == 9 && !options[0].IsEnabled, "fixed name and configurable data columns");
options[1].IsChecked = false;
options[1].RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent));
Check(grid.Columns[2].Visibility == Visibility.Collapsed, "hide column");
options[1].IsChecked = true;
options[1].RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent));
Check(grid.Columns[2].Visibility == Visibility.Visible, "show column");
Check(columns.ContextMenu.ActualWidth == 240, "column settings uses compact panel width");
Button done = (Button)columns.ContextMenu.Template.FindName("PART_DoneButton", columns.ContextMenu);
Check(done != null && done.Content.Equals("完成"), "column settings has a footer action");
System.Windows.Input.ApplicationCommands.Close.Execute(null, done);
Pump();
Check(!columns.ContextMenu.IsOpen, "done closes column settings");
grid.ShowCheckBox = false;
grid.ShowRowNumber = false;
grid.ShowToolbar = false;
grid.ShowPagination = false;
Pump();
Check(grid.RowHeaderWidth == 0 && grid.Columns[0].Visibility == Visibility.Collapsed, "independent header options");
grid.ShowCheckBox = true;
grid.ShowRowNumber = true;
grid.ShowToolbar = true;
grid.ShowPagination = true;
Pump();
Check(grid.RowHeaderWidth == 32 && grid.Columns[0].Visibility == Visibility.Visible, "restore options");
FrameworkElement defaultPagination = (FrameworkElement)grid.Template.FindName("PART_DefaultPagination", grid);
Check(defaultPagination.IsVisible, "default pagination visible without custom content");
Button customNext = new() { Content = "自定义下一页", Command = DataGridEx.NextPageCommand };
grid.PaginationContent = customNext;
Pump();
Check(customNext.IsVisible && !defaultPagination.IsVisible, "custom pagination replaces default");
Check(ReferenceEquals(customNext.DataContext, vm), "pagination inherits caller DataContext");
int previousPage = grid.PageIndex;
DataGridEx.NextPageCommand.Execute(null, customNext);
Pump();
Check(grid.PageIndex == previousPage + 1, "custom pagination routes page command");
grid.ShowPagination = false;
Pump();
Check(!customNext.IsVisible, "ShowPagination hides custom content");
grid.ShowPagination = true;
grid.PaginationContent = null;
Pump();
Check(defaultPagination.IsVisible, "clearing custom content restores default");
DataGridEx.FirstPageCommand.Execute(null, grid);
Button renew = new() { Content = "批量续期(模拟)" };
renew.SetBinding(Button.CommandProperty, new System.Windows.Data.Binding(nameof(DataGridTestViewModel.RenewCommand)) { Mode = System.Windows.Data.BindingMode.OneWay });
grid.ToolbarContent = renew;
Pump();
Check(ReferenceEquals(renew.Command, vm.RenewCommand), "toolbar inherits caller DataContext");
grid.SelectedItems.Add(grid.Items[0]);
vm.RenewCommand.Execute();
Check(vm.SelectedStores[0].ExpiresAt == new DateTime(2027, 5, 9), "batch command changes selected record");
vm.EmptyCommand.Execute();
Pump();
Check(grid.Items.Count == 0 && grid.PageIndex == 1 && grid.PageCount == 1 && !DataGridEx.NextPageCommand.CanExecute(null, grid), "empty page boundary");
vm.RestoreCommand.Execute();
Pump();
Check(grid.Items.Count == 20 && grid.TotalItemCount == 237, "restore keeps page size");
ICollectionView originalView = vm.CurrentItems;
Check(originalView is System.Windows.Data.ListCollectionView, "current page uses independent ListCollectionView");
Check(!ReferenceEquals(originalView, System.Windows.Data.CollectionViewSource.GetDefaultView(originalView.SourceCollection)), "view is independent from default collection view");
vm.CurrentItems.SortDescriptions.Clear();
vm.CurrentItems.SortDescriptions.Add(new SortDescription(nameof(DemoStore.StoreId), ListSortDirection.Descending));
DemoStore firstStore = vm.CurrentItems.Cast<DemoStore>().First();
vm.SelectedStores.Add(firstStore);
vm.LocalKeyword = firstStore.StoreId.ToUpperInvariant();
Pump();
Check(grid.Items.Count == 1 && vm.CurrentItems.Cast<DemoStore>().First() == firstStore && vm.TotalCount == 237 && vm.SelectedStores.Count == 0, "local search filters only loaded page and clears selection");
vm.LocalKeyword = "no-such-store";
Pump();
Check(grid.Items.Count == 0 && grid.PageCount == 12, "local no matches preserves pagination");
vm.LocalKeyword = string.Empty;
Pump();
Check(grid.Items.Count == 20, "clearing local search restores current page");
Check(ReferenceEquals(originalView, vm.CurrentItems) && vm.CurrentItems.SortDescriptions.Count == 1 &&
vm.CurrentItems.Cast<DemoStore>().First() == firstStore, "local filter preserves view identity and sorting");
DataGridEx.NextPageCommand.Execute(null, grid);
Pump();
DemoStore secondPageStore = vm.CurrentItems.Cast<DemoStore>().First();
vm.BackendKeyword = secondPageStore.StoreId;
Check(vm.TotalCount == 237 && grid.PageIndex == 2, "typing backend keyword does not search");
vm.LocalKeyword = "no-such-store";
RunSearch(vm, grid);
Pump();
Check(vm.LocalKeyword == string.Empty && grid.PageIndex == 1 && vm.TotalCount == 1 && vm.CurrentItems.Cast<DemoStore>().Single() == secondPageStore, "backend query searches all data and resets page/local filter");
vm.BackendKeyword = "小店";
RunSearch(vm, grid);
Pump();
Check(vm.TotalCount == 237 && grid.Items.Count == 20, "backend results paginate");
DataGridEx.NextPageCommand.Execute(null, grid);
Pump();
Check(vm.CurrentItems.Cast<DemoStore>().First() == secondPageStore, "backend query results persist across pages");
Check(ReferenceEquals(originalView, vm.CurrentItems), "paging and backend search retain independent view");
vm.BackendKeyword = "no-such-store";
RunSearch(vm, grid);
Pump();
Check(vm.TotalCount == 0 && grid.Items.Count == 0 && grid.PageIndex == 1, "backend no results");
vm.BackendKeyword = string.Empty;
RunSearch(vm, grid);
Pump();
Check(vm.TotalCount == 237 && grid.Items.Count == 20, "empty backend keyword restores all results");
Check(errors.Messages.Count == 0, "binding errors: " + string.Join(Environment.NewLine, errors.Messages));
Console.WriteLine("PASS: template loading, Bogus data, separate selection/number columns, tri-state selection, VM synchronization, paging, sorting/recycling numbers, column settings, visibility toggles and toolbar commands.");
return 0;
}
catch (Exception exception)
{
Console.Error.WriteLine(exception);
return 1;
}
finally
{
window?.Close();
app.Shutdown();
}
}
private static void RunSearch(DataGridTestViewModel vm, DataGridEx grid)
{
Task search = Dispatcher.CurrentDispatcher.Invoke(() => vm.SearchCommand.Execute());
Pump();
FrameworkElement overlay = (FrameworkElement)grid.Template.FindName("PART_LoadingOverlay", grid);
FrameworkElement table = (FrameworkElement)grid.Template.FindName("PART_TableArea", grid);
ProgressBar progress = (ProgressBar)grid.Template.FindName("PART_LoadingProgress", grid);
Check(vm.LoadingStatus.IsLoading && overlay.IsVisible && progress.IsIndeterminate && !table.IsEnabled, "loading animation and interaction lock");
Check(!vm.SearchCommand.CanExecute(), "prevent duplicate searches");
Stopwatch timeout = Stopwatch.StartNew();
while (!search.IsCompleted && timeout.Elapsed < TimeSpan.FromSeconds(5))
{
Pump();
Thread.Sleep(10);
}
Check(search.IsCompleted, "search completes");
search.GetAwaiter().GetResult();
Pump();
Check(!overlay.IsVisible && !progress.IsIndeterminate && table.IsEnabled, "loading animation stops and interaction restored");
}
private static void Pump() => Dispatcher.CurrentDispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle);
private static void Check(bool condition, string message)
{
if (!condition)
{
throw new InvalidOperationException(message);
}
}
private static IEnumerable<T> Descendants<T>(DependencyObject parent) where T : DependencyObject
{
for (int index = 0; index < VisualTreeHelper.GetChildrenCount(parent); index++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, index);
if (child is T match)
{
yield return match;
}
foreach (T descendant in Descendants<T>(child))
{
yield return descendant;
}
}
}
private sealed class BindingErrors : TraceListener
{
public List<string> Messages { get; } = [];
public override void Write(string? message) { }
public override void WriteLine(string? message)
{
if (!string.IsNullOrWhiteSpace(message))
{
Messages.Add(message);
}
}
}
}
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../Source/Store.Management/Store.Management.csproj"/>
</ItemGroup>
</Project>