Compare commits

..
10 Commits
Author SHA1 Message Date
chfei 440510aa8c 增加商铺列表 2026-11-16 12:17:45 +08:00
chfei d5232c581c 跟新颜色配置 2026-11-16 10:34:33 +08:00
chfei 45829fa267 更新代码 2026-11-13 19:19:33 +08:00
chfei 127fc22de5 提交用户部分代码 2026-11-13 15:51:16 +08:00
chfei 9b9e4cbd82 增加ViewModelBase 生命周期控制View 2026-11-13 11:07:41 +08:00
chfei 30a6a5ea24 增加MessageBoxService服务 2026-11-13 10:16:43 +08:00
chfei 3dcb6a1c34 修改代码 2026-11-12 18:22:14 +08:00
chfei f03e2b08f4 Main页面 2026-11-11 14:33:39 +08:00
chfei a003d90b0e 1 2026-11-10 16:33:51 +08:00
chfei 3135189ea3 修改部分bug 2026-10-28 17:56:50 +08:00
113 changed files with 58559 additions and 1034 deletions

No files matched your search

+4 -9
View File
@@ -359,16 +359,11 @@ if (AppFileHelper.PickFolder(out string path)) { FolderPath = path; }
XAML 细则见 `wpf-xaml.mdc`。 XAML 细则见 `wpf-xaml.mdc`。
## 数据映射(忽略) ## 服务端实体与 WPF 展示模型
使用 Mapster: - 服务端返回的业务实体命名为 `XxxInfo`(如 `UserInfo`),放在独立的 `Store.Management.Models` 项目中,可脱离 API 和 WPF 使用。
- WPF 视图绑定展示模型。单个实体的展示模型命名为 `XxxViewModel`(如 `UserViewModel`),集合中的每个元素命名为 `XxxItemViewModel`(如 `IReadOnlyList<UserItemViewModel>` 中的 `UserItemViewModel`)。
```csharp - 从服务端实体到展示模型的转换使用 Riok.Mapperly,映射类放在使用方项目的 `Mappers/` 目录。
using PipeReviewReport.Shared;
var dto = model.Adapt<XxxDto>();
var model = dto.Adapt<XxxModel>();
```
## 资源引用(忽略) ## 资源引用(忽略)
+82 -38
View File
@@ -6,6 +6,8 @@ globs: "**/*.xaml"
# XAML 视图编写约定 # XAML 视图编写约定
项目 XAML 默认不添加 `AutomationProperties.Name`。
## View XAML 头部模板 ## View XAML 头部模板
```XML ```XML
@@ -13,35 +15,55 @@ globs: "**/*.xaml"
x:Class="xxxxx.(xxxx)?.Views.XxxView" x:Class="xxxxx.(xxxx)?.Views.XxxView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 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:xxxx.(xxxx)?.Views" xmlns:local="clr-namespace:xxxx.(xxxx)?.Views"
xmlns:core="MAX.Core" xmlns:core="MAX.Core"
xmlns:hc="https://handyorg.github.io/handycontrol" xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:wpf="MAX.WPF" xmlns:wpf="MAX.WPF"
xmlns:s="clr-namespace:xxxx.xxx;assembly=xxx.xxx" xmlns:s="clr-namespace:xxxx.xxx;assembly=xxx.xxx"
d:DataContext="{d:DesignInstance Type=local:XxxViewModel}"
Style="{DynamicResource UserControlStyle}" Style="{DynamicResource UserControlStyle}"
DataContext="{core:DISource Type=local:XxxViewModel}" DataContext="{core:DISource Type=local:XxxViewModel}"
d:DataContext="{d:DesignInstance Type=local:XxxViewModel}"
d:Background="White"
d:DesignHeight="450" d:DesignHeight="450"
d:DesignWidth="800"> d:DesignWidth="800"
mc:Ignorable="d"
>
``` ```
## Dialog View XAML ## Dialog View XAML
```XML ```XML
<UserControl <UserControl
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:core="MAX.Core" xmlns:core="MAX.Core"
xmlns:hc="https://handyorg.github.io/handycontrol" xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:wpf="MAX.WPF" xmlns:wpf="MAX.WPF"
d:Background="White" d:Background="White"
d:DataContext="{d:DesignInstance Type=local:DialogViewModel}" d:DataContext="{d:DesignInstance Type=local:DialogViewModel}"
Style="{StaticResource DialogStyle.Base}" Style="{StaticResource DialogStyle.Base}"
DataContext="{core:DISource Type=local:DialogViewModel}"> DataContext="{core:DISource Type=local:DialogViewModel}"
mc:Ignorable="d"
>
``` ```
- `{core:DISource Type=local:XxxViewModel}` 绑定 ViewModel - `{core:DISource Type=local:XxxViewModel}` 绑定 ViewModel
- `d:DataContext="{d:DesignInstance Type=local:XxxViewModel}"` 提供设计时数据 - `d:DataContext="{d:DesignInstance Type=local:XxxViewModel}"` 提供设计时数据
- `UserControlStyle` 与 `ViewModelBaseEx` 强相关,必须搭配使用 - `UserControlStyle` 与 `ViewModelBaseEx` 强相关,必须搭配使用
### 控件必须有设计数据
页面、弹窗和 `DataTemplate` 应能在 XAML 设计器中直接看出字段内容、排列方向、对齐和间距。设计值使用 `d:` 命名空间,根元素声明 `xmlns:d`、`xmlns:mc` 和 `mc:Ignorable="d"`,保留运行时绑定。
- `TextBox`、`TextBlock` 的文本来自绑定或默认为空时,必须设置有业务含义的非空示例,如 `d:Text="示例商贸有限公司"`。静态文案已可见时无需重复填写。
- 绑定集合的 `ItemsControl`、`ListBox`、`ComboBox`、`DataGridEx` 等必须提供设计时数据,默认使用 `d:ItemsSource="{d:SampleData ItemCount=5}"`。行数可按实际布局调整。下拉框要预览选中项时可加 `d:SelectedIndex="0"`。
- 其他控件按实际显示属性提供设计值,例如绑定标题的 `wpf:TitleContent` 用 `d:Title="中转仓快递费(元/单)"`,金额输入框用 `d:Value="2.20"`,绑定按钮文案用 `d:Content="保存"`。运行时按状态显示的区域,可用 `d:Visibility="Visible"` 预览。
- 集合模板既要能看到多行,也要能看清每行内容。若样本数据未填充自定义控件的显示属性,在模板内补相应的 `d:` 值。
## BindingProxy + CommandProxy(DataTemplate/ContextMenu 绑定) ## BindingProxy + CommandProxy(DataTemplate/ContextMenu 绑定)
**在 `DataTemplate`、`ContextMenu`、`DataGridTemplateColumn.CellTemplate` 中禁止使用 `RelativeSource AncestorType`,必须用 `BindingProxy` + `CommandProxy`。** **在 `DataTemplate`、`ContextMenu`、`DataGridTemplateColumn.CellTemplate` 中禁止使用 `RelativeSource AncestorType`,必须用 `BindingProxy` + `CommandProxy`。**
@@ -60,6 +82,9 @@ DataContext="{core:DISource Type=local:DialogViewModel}">
**`BindingProxy` 映射关系**:`Data="{Binding}"` 把 ViewModel 存到 `BindingProxy.Data`。引用时 `Path=Data.SelectedItem` 中 `Data` 对应 `BindingProxy.Data`(即 ViewModel)。 **`BindingProxy` 映射关系**:`Data="{Binding}"` 把 ViewModel 存到 `BindingProxy.Data`。引用时 `Path=Data.SelectedItem` 中 `Data` 对应 `BindingProxy.Data`(即 ViewModel)。
### 文字只读显示
尽量使用 `TextBlock` 而不是 `Label`
### DataTemplate(CellTemplate)中 ### DataTemplate(CellTemplate)中
Command 用 CommandProxy,行数据用 `{Binding}`: Command 用 CommandProxy,行数据用 `{Binding}`:
@@ -262,6 +287,39 @@ C# 侧:`"#FF5733".toColor()`、`"#80000000".toColor()`。
</Style> </Style>
``` ```
## 顺序排列与间距布局
**页面排版需要横向、纵向顺序排列或简单自动换行时,优先使用 `wpf:SpacingStackPanel`。** 普通堆叠布局通过 `Orientation` 指定方向,需要换行时设置 `ChildWrapping="True"`。
- 优先用 `HorizontalSpacing` / `VerticalSpacing` 统一控制子项间距,避免逐项设置重复的 `Margin`;容器外边距和个别元素的特殊偏移仍按需使用 `Margin`。
- 需要统一子项尺寸或对齐时,按需设置 `ItemWidth`、`ItemHeight`、`ItemHorizontalAlignment`、`ItemVerticalAlignment`。
- “文字 + 简单内容”可由 `wpf:TitleContent` 组成,再用 `wpf:SpacingStackPanel` 排列多个字段。
- 需要行列划分、跨行跨列、重叠或虚拟化时,使用满足这些要求的布局容器,不强行替换为 `SpacingStackPanel`。
- 属性及用法见 [max-common-wpf SpacingStackPanel 参考](../skills/max-common-wpf/references/api.md#controlsspacingstackpanelcs)。
### ItemsControl 的顺序排版
少量集合项按行或列顺序排列时,必须在 `ItemsControl.ItemsPanel` 的 `ItemsPanelTemplate` 中使用 `wpf:SpacingStackPanel`。项与项之间的间距由这个面板控制;`ItemTemplate` 负责单项内部布局。优先复用已有间距样式,例如计费弹窗的 `VerticalSpacingPanel4`。需要虚拟化的长列表保留虚拟化面板。
```xml
<ItemsControl ItemsSource="{Binding Fields, Mode=OneWay}"
d:ItemsSource="{d:SampleData ItemCount=5}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<wpf:SpacingStackPanel Style="{StaticResource VerticalSpacingPanel4}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
```
## 文字与简单内容布局
**页面排版遇到“说明文字 + 简单内容”(如输入框、选择器、按钮等输入或点击控件)时,优先使用 `wpf:TitleContent`。** 将说明文字放在 `Title`,交互控件作为内容,避免为同一组合另用 `TextBlock` 配合 `Grid` / `StackPanel` 手工拼接。
- 按布局设置 `Placement`;左侧标题表单优先使用 `Placement="Left"`,并按需设置 `TitleWidth`、`TitleVerticalAlignment="Center"` 和 `LeftTitlePadding`,保持同组字段对齐。
- 内容控件仍自行配置绑定、命令和输入长度;`TitleContent` 只负责标题与内容的布局。
- 属性及用法见 [max-common-wpf TitleContent 参考](../skills/max-common-wpf/references/api.md#controlstitlecontentcs)。
## 布局注释 ## 布局注释
主要布局分块/区域前加 `<!-- -->` 注释标明用途。复杂视图(多面板、多 Tab、对话框)必须注释;简单单控件视图可省略: 主要布局分块/区域前加 `<!-- -->` 注释标明用途。复杂视图(多面板、多 Tab、对话框)必须注释;简单单控件视图可省略:
@@ -302,48 +360,34 @@ C# 侧:`"#FF5733".toColor()`、`"#80000000".toColor()`。
## 枚举绑定 ## 枚举绑定
### EnumDisplayConverter(XAML) **页面的枚举选项绑定优先使用 `EnumBindingMarkup`(`EnumBindingMarkupExtension`)生成 ItemsSource,配合 `EnumBindingExtension.SelectedEnum` 绑定选中的枚举值。** 不要仅为列出枚举值,在 ViewModel 中额外定义 `Enum.GetValues` 列表或在 XAML 中硬编码选项。
- 显示名优先使用 MAX.Common.WPF 自带的 `EnumDisplayConverter`,显式传入标记扩展的 `Converter`;未传入时默认显示枚举成员名称。
- `DisplayMemberPath="Display"` 用于显示名称,`SelectedValuePath="Value"` 对应枚举值本身。
- 系统初始化、视图加载前配置一次 `EnumDisplayConverter.EnumDisplayManager = new EnumDisplayManagerWPF(null);`;已有自定义显示管理器时复用现有配置。
- 仅显示单个枚举值的文本时,直接绑定该属性并使用 `EnumDisplayConverter`,无需生成选项列表。
### ComboBox 绑定枚举
`xmlns:wpf="MAX.WPF"`,`xmlns:local` 指向业务枚举命名空间:
```xml ```xml
<UserControl.Resources> <UserControl.Resources>
<conv:EnumDisplayConverter x:Key="EnumDisplayConverter"/> <wpf:EnumDisplayConverter x:Key="EnumDisplayConverter" />
</UserControl.Resources> </UserControl.Resources>
<!-- 直接绑定枚举值 --> <ComboBox
<TextBlock Text="{Binding Status, Converter={StaticResource EnumDisplayConverter}}"/> ItemsSource="{wpf:EnumBindingMarkup EnumType={x:Type local:MyStatus},
Converter={StaticResource EnumDisplayConverter}}"
DisplayMemberPath="Display"
SelectedValuePath="Value"
wpf:EnumBindingExtension.SelectedEnum="{Binding SelectedStatus, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<!-- 只读显示单个枚举值 -->
<TextBlock Text="{Binding Status, Mode=OneWay, Converter={StaticResource EnumDisplayConverter}}" />
``` ```
### ComboBox 绑定枚举(推荐:ViewModel 提供列表) 初始化命名空间、Description 显示、空选项等完整用法见 [max-common-wpf 枚举绑定参考](../skills/max-common-wpf/references/api.md#markupextensionsenumbindingmarkupextensioncs)。自定义枚举显示管理器见 `reference-enum-display` skill。
```csharp
// ViewModel
public IReadOnlyList<MyStatus> StatusList { get; } = Enum.GetValues(typeof(MyStatus)).Cast<MyStatus>().ToList();
public MyStatus SelectedStatus
{
get => GetProperty(() => SelectedStatus);
set => SetProperty(() => SelectedStatus, value);
}
```
```xml
<ComboBox ItemsSource="{Binding StatusList}"
SelectedItem="{Binding SelectedStatus}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ., Converter={StaticResource EnumDisplayConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
```
### C# 获取枚举显示文本
```csharp
string displayText = MyStatus.Active.GetEnumDisplay();
```
EnumDisplayService 内部实现和自定义逻辑详见 `reference-enum-display` skill。
## MarkupExtension 示例 ## MarkupExtension 示例
+2 -2
View File
@@ -24,7 +24,7 @@ disable-model-invocation: false
```csharp ```csharp
using MAX.Core.DependencyInjections; using MAX.Core.DependencyInjections;
namespace PipeReviewReport.<模块名>.Services; namespace 项目.<模块名>.Services;
public interface IXxxService public interface IXxxService
{ {
@@ -43,7 +43,7 @@ internal class XxxService : IXxxService, ISingletonDependency
using MAX.Core.DependencyInjections; using MAX.Core.DependencyInjections;
using MAX.Core.Interfaces; using MAX.Core.Interfaces;
namespace PipeReviewReport.<模块名>.Services; namespace 项目.<模块名>.Services;
public interface IXxxService { } public interface IXxxService { }
+10 -13
View File
@@ -18,6 +18,8 @@ description: 在 Windows WPF 项目中接入和使用 MAX.Common.WPF 的控件
按任务读取 [功能索引](references/features.md)。具体命名空间、属性和方法在 [常用 API 声明](references/api.md) 中按类型搜索。声明摘录没有完整方法体;行为不明确时查看当前安装包 XML 文档、反射或可用源码,再以编译和运行验证。消费项目没有原仓库也应能使用本指南。 按任务读取 [功能索引](references/features.md)。具体命名空间、属性和方法在 [常用 API 声明](references/api.md) 中按类型搜索。声明摘录没有完整方法体;行为不明确时查看当前安装包 XML 文档、反射或可用源码,再以编译和运行验证。消费项目没有原仓库也应能使用本指南。
标题布局与间距布局分别参见 [TitleContent 用法](references/api.md#controlstitlecontentcs) 和 [SpacingStackPanel 用法](references/api.md#controlsspacingstackpanelcs)。
## XAML 资源入口 ## XAML 资源入口
程序集声明了 `xmlns:wpf="MAX.WPF"`。控件样式和共享转换器位于 `Resources/Generic.xaml`,不要猜成 `Themes/Generic.xaml`。需要这些资源时,在现有 Application.Resources 的 MergedDictionaries 中合并一次: 程序集声明了 `xmlns:wpf="MAX.WPF"`。控件样式和共享转换器位于 `Resources/Generic.xaml`,不要猜成 `Themes/Generic.xaml`。需要这些资源时,在现有 Application.Resources 的 MergedDictionaries 中合并一次:
@@ -26,12 +28,14 @@ description: 在 Windows WPF 项目中接入和使用 MAX.Common.WPF 的控件
<ResourceDictionary Source="/MAX.Common.WPF;component/Resources/Generic.xaml"/> <ResourceDictionary Source="/MAX.Common.WPF;component/Resources/Generic.xaml"/>
``` ```
页面最小示例(绑定属性由页面的 DataContext 提供): ## 页面最小示例
绑定属性由页面的 DataContext 提供:
```xml ```xml
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" <StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpf="MAX.WPF"> xmlns:wpf="MAX.WPF">
<StackPanel.Resources> <StackPanel.Resources>
<wpf:Boolean2VisibilityConverter x:Key="ShowWhenTrue"/> <wpf:Boolean2VisibilityConverter x:Key="ShowWhenTrue"/>
</StackPanel.Resources> </StackPanel.Resources>
@@ -55,18 +59,11 @@ description: 在 Windows WPF 项目中接入和使用 MAX.Common.WPF 的控件
- 虚拟化依赖有限可视区域、滚动宿主和 ItemsPanel 配置。`VirtualizingItemsControl` 默认使用 VirtualizingStackPanel,需要换行时显式设置 VirtualizingWrapPanel。不能仅添加面板便承诺大数据性能。 - 虚拟化依赖有限可视区域、滚动宿主和 ItemsPanel 配置。`VirtualizingItemsControl` 默认使用 VirtualizingStackPanel,需要换行时显式设置 VirtualizingWrapPanel。不能仅添加面板便承诺大数据性能。
- 通用命令在 `MAX.Common.Commands`,不是 WPF.Commands。MethodCommand<T> / AsyncMethodCommand<T> 的 T 需引用类型或可空值类型,状态变化手动 RaiseCanExecuteChanged;异步命令委托需自行处理业务异常。 - 通用命令在 `MAX.Common.Commands`,不是 WPF.Commands。MethodCommand<T> / AsyncMethodCommand<T> 的 T 需引用类型或可空值类型,状态变化手动 RaiseCanExecuteChanged;异步命令委托需自行处理业务异常。
## 枚举绑定示例 ## 枚举绑定
已有 `xmlns:local` 指向业务枚举命名空间、`SelectedStatus` 是 `Status` 属性时: 枚举显示优先使用 MAX.Common.WPF 自带的 `EnumDisplayConverter`,并通过 `EnumBindingMarkupExtension.Converter` 显式传入;未设置转换器时只显示枚举成员名称。系统初始化时、视图加载前配置一次 `EnumDisplayConverter.EnumDisplayManager = new EnumDisplayManagerWPF(null);`;已有自定义管理器时复用现有配置。
```xml 初始化代码、Description 显示示例及选中值绑定见 [枚举绑定用法](references/api.md#markupextensionsenumbindingmarkupextensioncs)。
<ComboBox ItemsSource="{wpf:EnumBindingMarkup EnumType={x:Type local:Status}}"
DisplayMemberPath="Display"
SelectedValuePath="Value"
wpf:EnumBindingExtension.SelectedEnum="{Binding SelectedStatus, Mode=TwoWay}"/>
```
允许空选项时使用 AllowNull 并让业务属性可空;自定义显示通过扩展的 Converter 提供,勿假设自动读取所有枚举描述标记。
## 验证与交付 ## 验证与交付
+191 -1
View File
@@ -2,12 +2,18 @@
来源:MAX.Common.WPF,2026-10-27 工作区源码快照。 来源:MAX.Common.WPF,2026-10-27 工作区源码快照。
按下方主题或文件名搜索。仅摘录选定文件的 public / protected 声明;省略方法体、初始化表达式与 XML 注释。这是定位参考,不是可直接编译的 C#,不保证包含嵌套类型的完整可见性上下文。行为说明见 SKILL.md;目标包版本不同时以实际包为准。 按下方主题或文件名搜索。API 代码块仅摘录选定文件的 public / protected 声明;省略方法体、初始化表达式与 XML 注释。TitleContent 与 SpacingStackPanel 另附属性说明和 XAML 用法。这是定位参考,不是可直接编译的 C#,不保证包含嵌套类型的完整可见性上下文。通用集成约束见 SKILL.md;目标包版本不同时以实际包为准。
目录:控件与布局、枚举、视图与绑定、线程与防抖、虚拟化与转换器 目录:控件与布局、枚举、视图与绑定、线程与防抖、虚拟化与转换器
## 控件与布局 ## 控件与布局
以下 TitleContent 与 SpacingStackPanel 示例在视图根元素声明命名空间:
```xml
xmlns:max="clr-namespace:MAX.Common.WPF.Controls;assembly=MAX.Common.WPF"
```
### Controls/NumberBox.cs ### Controls/NumberBox.cs
命名空间:`MAX.Common.WPF.Controls` 命名空间:`MAX.Common.WPF.Controls`
@@ -46,6 +52,55 @@ public Thickness LeftTitlePadding
public TitleContent() public TitleContent()
``` ```
`TitleContent` 是一个"标题 + 内容"布局控件:在 `Content` 周围额外渲染一个 `Title`,并可通过 `Placement` 决定标题相对内容的位置,同时支持标题宽度、对齐方式与内边距的精细控制。
| 属性 | 类型 | 默认值 | 说明 |
| :--- | :--- | :--- | :--- |
| `Content` | `object` | — | 继承自 `ContentControl`,主内容 |
| `Title` | `object` | `null` | 标题内容(可放字符串、任意 UIElement) |
| `Placement` | `TitlePlacementType` | `Top` | 标题相对内容的位置 |
| `TitleWidth` | `double` | `NaN` | 标题宽度;`NaN` 表示自动(Auto) |
| `TitleHorizontalAlignment` | `HorizontalAlignment` | `Left` | 标题在自身区域内的水平对齐 |
| `TitleVerticalAlignment` | `VerticalAlignment` | `Top` | 标题在自身区域内的垂直对齐 |
| `TopTitlePadding` | `Thickness` | `(7,2,0,1)` | `Placement=Top` 时标题的内边距 |
| `LeftTitlePadding` | `Thickness` | `(0,0,6,0)` | `Placement=Left` 时标题的内边距 |
标题位置示例使用 Top 与 Left;其他枚举值以实际程序集为准,不根据 padding 属性名推断。
#### 1. 最简用法(标题在上)
```xml
<max:TitleContent Title="用户名">
<TextBox />
</max:TitleContent>
```
#### 2. 标题在左侧 + 固定标题宽度(表单场景)
```xml
<max:TitleContent Title="用户名"
Placement="Left"
TitleWidth="80"
TitleVerticalAlignment="Center"
LeftTitlePadding="0,0,8,0">
<TextBox />
</max:TitleContent>
```
#### 3. 标题使用复杂 UIElement
```xml
<max:TitleContent Placement="Top">
<max:TitleContent.Title>
<StackPanel Orientation="Horizontal">
<TextBlock Text="密码" />
<TextBlock Text="*" Foreground="Red" />
</StackPanel>
</max:TitleContent.Title>
<PasswordBox />
</max:TitleContent>
```
### Controls/BoolContent.cs ### Controls/BoolContent.cs
命名空间:`MAX.Common.WPF.Controls` 命名空间:`MAX.Common.WPF.Controls`
@@ -74,6 +129,87 @@ public HorizontalAlignment? ItemHorizontalAlignment
public VerticalAlignment? ItemVerticalAlignment public VerticalAlignment? ItemVerticalAlignment
``` ```
> `SpacingStackPanel` 是一个"带间距 + 可选自动换行 + 可选统一子项尺寸"的布局面板,可看作 `StackPanel` 的增强版:既支持 StackPanel 式的单向排列,也支持 `WrapPanel` 式的换行排列,并且可以在**每个子项之间**插入水平/垂直间距。
#### 核心属性速查
| 属性 | 类型 | 默认值 | 说明 |
| :--- | :--- | :--- | :--- |
| `Orientation` | `Orientation` | `Horizontal` | 排列方向(水平/垂直),影响"主轴"与间距的解释 |
| `ChildWrapping` | `bool` | `false` | 是否自动换行(类似 WrapPanel);`false` 时类似 StackPanel |
| `HorizontalSpacing` | `double` | `NaN`(视为 0) | 子项之间的水平间距;校验要求 `> 0` 或 `NaN` |
| `VerticalSpacing` | `double` | `NaN`(视为 0) | 子项之间的垂直间距;校验要求 `> 0` 或 `NaN` |
| `ItemWidth` | `double` | `NaN`(自动) | 统一子项宽度;示例使用数值宽度,不将其当作 GridLength 的星号尺寸 |
| `ItemHeight` | `double` | `NaN`(自动) | 统一子项高度 |
| `ItemHorizontalAlignment` | `HorizontalAlignment?` | `Stretch` | 强制设置所有子项的 `HorizontalAlignment` |
| `ItemVerticalAlignment` | `VerticalAlignment?` | `Stretch` | 强制设置所有子项的 `VerticalAlignment` |
> 关键点:`HorizontalSpacing`/`VerticalSpacing` 不是"主轴/交叉轴"间距,而是**屏幕坐标意义上的水平/垂直间距**。当 `Orientation=Horizontal` 时通常用 `HorizontalSpacing` 拉开子项;`Orientation=Vertical` 时通常用 `VerticalSpacing` 拉开子项。
#### XAML 基本用法
示例沿用本节开头的 max 命名空间声明。
##### 1. 水平排列 + 子项水平间距(最常用)
```xml
<max:SpacingStackPanel Orientation="Horizontal" HorizontalSpacing="8">
<Button Content="确定" />
<Button Content="取消" />
<Button Content="应用" />
</max:SpacingStackPanel>
```
##### 2. 垂直排列 + 行间距
```xml
<max:SpacingStackPanel Orientation="Vertical" VerticalSpacing="6">
<TextBlock Text="第一行" />
<TextBlock Text="第二行" />
<TextBlock Text="第三行" />
</max:SpacingStackPanel>
```
##### 3. 自动换行(标签云 / 按钮流)
```xml
<max:SpacingStackPanel Orientation="Horizontal"
ChildWrapping="True"
HorizontalSpacing="8"
VerticalSpacing="8">
<Button Content="标签1" />
<Button Content="标签2" />
<Button Content="标签3" />
<!-- ... -->
</max:SpacingStackPanel>
```
##### 4. 统一子项尺寸(等宽卡片网格)
```xml
<max:SpacingStackPanel Orientation="Horizontal"
ChildWrapping="True"
ItemWidth="120"
ItemHeight="80"
HorizontalSpacing="10"
VerticalSpacing="10">
<Border Background="#EEE" />
<Border Background="#EEE" />
<Border Background="#EEE" />
</max:SpacingStackPanel>
```
##### 5. 控制子项对齐
```xml
<max:SpacingStackPanel Orientation="Horizontal"
HorizontalSpacing="8"
ItemVerticalAlignment="Center">
<TextBlock Text="姓名:" />
<TextBox Width="160" />
</max:SpacingStackPanel>
```
### Controls/SpacingUniformGrid.cs ### Controls/SpacingUniformGrid.cs
命名空间:`MAX.Common.WPF.Controls` 命名空间:`MAX.Common.WPF.Controls`
@@ -156,6 +292,60 @@ public override bool Equals(object obj)
public override int GetHashCode() public override int GetHashCode()
``` ```
#### 显示名称与库自带转换器
MAX.Common.WPF 已提供 `EnumDisplayConverter`,枚举显示优先复用它,不必另写读取 Description 的转换器。`EnumBindingMarkupExtension` 不会自动使用这个转换器,必须通过 `Converter` 显式传入:
- `Value` 保存枚举值本身,例如 `EEE.Admin`。
- 未设置 `Converter` 时,`Display` 为枚举值的 `ToString()`,例如 `"Admin"`,不会由标记扩展直接读取 `Description`。
- 设置 `EnumDisplayConverter` 后,`Display` 由枚举显示管理器生成;界面仍绑定 `Display`,选中值绑定 `Value`。
#### 系统初始化
`EnumDisplayConverter` 提供全局静态属性 `public static EnumDisplayManagerBase EnumDisplayManager { get; set; }`。在系统初始化、相关视图加载之前设置一次:
```csharp
using MAX.Common.WPF.Converters;
using MAX.Common.WPF.Utilities;
EnumDisplayConverter.EnumDisplayManager = new EnumDisplayManagerWPF(null);
```
将赋值放进项目已有的启动初始化流程;若已配置自定义显示管理器,复用现有配置,不要重复覆盖。
#### Description 显示示例
```csharp
using System.ComponentModel;
public enum EEE
{
[Description("管理员")]
Admin,
[Description("用户")]
User
}
```
`xmlns:wpf="MAX.WPF"`,`xmlns:local` 指向枚举所在命名空间。在视图资源中注册库自带转换器,再将它传给标记扩展:
```xml
<UserControl.Resources>
<wpf:EnumDisplayConverter x:Key="EnumDisplayConverter" />
</UserControl.Resources>
<ComboBox
ItemsSource="{wpf:EnumBindingMarkup EnumType={x:Type local:EEE},
Converter={StaticResource EnumDisplayConverter}}"
DisplayMemberPath="Display"
SelectedValuePath="Value"
wpf:EnumBindingExtension.SelectedEnum="{Binding SelectedRole, Mode=TwoWay}" />
```
`SelectedRole` 是带属性变更通知的 `EEE` 属性。界面显示“管理员”“用户”,选中值仍为 `EEE.Admin` 或 `EEE.User`。只需要展示选项时,可以省略 `SelectedValuePath` 和 `SelectedEnum` 绑定。
允许空选项时设置 `AllowNull=True`,并让选中属性可空。`NullDisplay` 默认为空字符串;只有显式设置为 null 时,标记扩展才会尝试调用转换器生成空选项的显示内容。`DisplayNullLast` 控制空选项是否放在末尾。
### Extensions/EnumBindingExtension.cs ### Extensions/EnumBindingExtension.cs
命名空间:`MAX.Common.WPF.Extensions` 命名空间:`MAX.Common.WPF.Extensions`
@@ -5,8 +5,8 @@
| 需求 | 类型 / 命名空间 | 使用要点 | | 需求 | 类型 / 命名空间 | 使用要点 |
| --- | --- | --- | | --- | --- | --- |
| 数值输入 | Controls.NumberBox | Value 为 double;Minimum、Maximum、Increment、DecimalPlaces、ValueFormat、ShowUpDownButton;模板资源在 Resources/Generic.xaml | | 数值输入 | Controls.NumberBox | Value 为 double;Minimum、Maximum、Increment、DecimalPlaces、ValueFormat、ShowUpDownButton;模板资源在 Resources/Generic.xaml |
| 标题与条件内容 | Controls.TitleContent、BoolContent | TitleContent 有 Placement 等布局属性;BoolContent 用 Bool、TrueContent、FalseContent | | 标题与条件内容 | Controls.TitleContent、BoolContent | [TitleContent](api.md#controlstitlecontentcs) 提供标题位置、宽度、对齐和内边距,详见属性表与示例;BoolContent 用 Bool、TrueContent、FalseContent |
| 间距布局 | Controls.SpacingStackPanel、SpacingUniformGrid、AutoColumnsUniformGrid | 区分面板间距与子元素 Margin,按声明配置 | | 间距布局 | Controls.SpacingStackPanel、SpacingUniformGrid、AutoColumnsUniformGrid | [SpacingStackPanel](api.md#controlsspacingstackpanelcs) 支持水平/垂直间距、换行、统一子项尺寸与对齐,详见属性表与示例;区分面板间距与子元素 Margin |
| 图标与链接 | Controls.FontIcon、HyperlinkEx | FontIcon 继承 TextBlock,具体字体和字形必须与项目资源一致 | | 图标与链接 | Controls.FontIcon、HyperlinkEx | FontIcon 继承 TextBlock,具体字体和字形必须与项目资源一致 |
| 按钮与弹出层 | Controls.MenuButton、ButtonPopup、CustomPopup、ClippingBorder | 按实际属性处理关闭、焦点和裁切,不猜测通用 Popup 行为 | | 按钮与弹出层 | Controls.MenuButton、ButtonPopup、CustomPopup、ClippingBorder | 按实际属性处理关闭、焦点和裁切,不猜测通用 Popup 行为 |
| 托盘图标 | Controls.NotifyIcon;Enums.NotifyIconInfoType | 涉及 Win32 资源与应用生命周期,检查实际清理 API | | 托盘图标 | Controls.NotifyIcon;Enums.NotifyIconInfoType | 涉及 Win32 资源与应用生命周期,检查实际清理 API |
@@ -14,7 +14,7 @@
| 标准控件附加行为 | Extensions.TextBoxExtension、ButtonExtension、ListBoxExtension、TreeViewExtension、SelectorExtension、ScrollViewerExtension、ProgressBarExtension、ToolTipExtension | 搜索对应 Get/Set 方法确认附加属性名称、默认值与事件机制 | | 标准控件附加行为 | Extensions.TextBoxExtension、ButtonExtension、ListBoxExtension、TreeViewExtension、SelectorExtension、ScrollViewerExtension、ProgressBarExtension、ToolTipExtension | 搜索对应 Get/Set 方法确认附加属性名称、默认值与事件机制 |
| 通用控件行为 | Extensions.ControlExtension(Context / DragDrop / Focus / Keyboard / Layout / Loaded / Mouse 分文件)、WindowExtension、GridLayoutHelper | 使用实际 API 名称,不把文件名当作附加属性名 | | 通用控件行为 | Extensions.ControlExtension(Context / DragDrop / Focus / Keyboard / Layout / Loaded / Mouse 分文件)、WindowExtension、GridLayoutHelper | 使用实际 API 名称,不把文件名当作附加属性名 |
| 上下文菜单和绑定代理 | Extensions.ContextMenuExtension、ContextMenuListener、BindingProxy / BooleanProxy、CommandProxy;Models.ContextMenuModel;ViewModels.ContextMenuViewModel | Popup/ContextMenu 不在普通可视树,核对 DataContext 来源 | | 上下文菜单和绑定代理 | Extensions.ContextMenuExtension、ContextMenuListener、BindingProxy / BooleanProxy、CommandProxy;Models.ContextMenuModel;ViewModels.ContextMenuViewModel | Popup/ContextMenu 不在普通可视树,核对 DataContext 来源 |
| 枚举选择与显示 | MarkupExtensions.EnumBindingMarkupExtension;Extensions.EnumBindingExtension;Converters.EnumDisplayConverter;Utilities.EnumDisplayManagerWPF | ItemsSource 返回包装对象;旧 EnumBindingComboBox 已弃用 | | 枚举选择与显示 | MarkupExtensions.EnumBindingMarkupExtension;Extensions.EnumBindingExtension;Converters.EnumDisplayConverter;Utilities.EnumDisplayManagerWPF | [枚举绑定用法](api.md#markupextensionsenumbindingmarkupextensioncs):显式传入库自带 EnumDisplayConverter,启动时初始化 EnumDisplayManager;ItemsSource 返回 Display/Value 包装对象;旧 EnumBindingComboBox 已弃用 |
| 布尔、空值与可见性 | Converters.Boolean2VisibilityConverter、Boolean2VisibilityReConverter、Object2VisibilityConverter、String2VisibilityConverter、IListToVisibilityConverter、BooleanArr2VisibilityConverter 等 | 各 Converter 对 null、空串、集合的定义不同,核对实现;多值转换器需 MultiBinding | | 布尔、空值与可见性 | Converters.Boolean2VisibilityConverter、Boolean2VisibilityReConverter、Object2VisibilityConverter、String2VisibilityConverter、IListToVisibilityConverter、BooleanArr2VisibilityConverter 等 | 各 Converter 对 null、空串、集合的定义不同,核对实现;多值转换器需 MultiBinding |
| 格式、颜色、尺寸转换 | Converters.FileSizeDisplayConverter、DateTimeFormatConverter、FormatConverter、StringJoinConverter、ColorToBrushConverter、ContrastBrushConverter、ThicknessSplitConverter、CornerRadiusSplitConverter 等 | 按 IValueConverter / IMultiValueConverter 及 ConvertBack 支持情况选择绑定模式 | | 格式、颜色、尺寸转换 | Converters.FileSizeDisplayConverter、DateTimeFormatConverter、FormatConverter、StringJoinConverter、ColorToBrushConverter、ContrastBrushConverter、ThicknessSplitConverter、CornerRadiusSplitConverter 等 | 按 IValueConverter / IMultiValueConverter 及 ConvertBack 支持情况选择绑定模式 |
| 视图生命周期 | ViewModels.ViewModelBase;Extensions.ViewModelExtension | LoadedOnce / Loaded / Unloaded;关联视图并非 IoC 自动创建 ViewModel | | 视图生命周期 | ViewModels.ViewModelBase;Extensions.ViewModelExtension | LoadedOnce / Loaded / Unloaded;关联视图并非 IoC 自动创建 ViewModel |
+1 -1
View File
@@ -28,7 +28,7 @@ disable-model-invocation: false
| 文件 | 加载策略 | 内容范围 | | 文件 | 加载策略 | 内容范围 |
|---|---|---| |---|---|---|
| `.agents/rules/wpf-core.md` | alwaysApply: true | 项目结构、命名约定、ViewModel、MVVM属性、Command、服务、DI、对话框、LoadingStatus、文件对话框/文件夹选择、输入限长、Mapster | | `.agents/rules/wpf-core.md` | alwaysApply: true | 项目结构、命名约定、ViewModel、MVVM属性、Command、服务、DI、对话框、LoadingStatus、文件对话框/文件夹选择、输入限长、实体与展示模型映射 |
| `.agents/rules/csharp-syntax.md` | alwaysApply: true | C# 语法硬约束(禁止 var、null检查、Debug.WriteLine、DRY等) | | `.agents/rules/csharp-syntax.md` | alwaysApply: true | C# 语法硬约束(禁止 var、null检查、Debug.WriteLine、DRY等) |
| `.agents/rules/architecture.md` | alwaysApply: true | 技术栈、项目架构、编译校验 | | `.agents/rules/architecture.md` | alwaysApply: true | 技术栈、项目架构、编译校验 |
| `.agents/rules/editor-conventions.md` | alwaysApply: true | 换行符、编码规范 | | `.agents/rules/editor-conventions.md` | alwaysApply: true | 换行符、编码规范 |
+15 -3
View File
@@ -26,12 +26,24 @@ button,input,select{border-radius:2px;font-size:12px}button{padding:3px 10px;hei
th:first-child,td:first-child{width:30px;min-width:30px;padding:0 8px;position:sticky;left:0;background:white;z-index:1}th:first-child{background:#f0f2f4;z-index:3}.row-number{color:#9299a1;text-align:right;font-size:11px;min-width:34px}thead th{z-index:2}th:last-child{z-index:3;background:#f0f2f4}td:last-child,th:last-child{box-shadow:-3px 0 4px #0000000a;border-left:1px solid #dce0e4} th:first-child,td:first-child{width:30px;min-width:30px;padding:0 8px;position:sticky;left:0;background:white;z-index:1}th:first-child{background:#f0f2f4;z-index:3}.row-number{color:#9299a1;text-align:right;font-size:11px;min-width:34px}thead th{z-index:2}th:last-child{z-index:3;background:#f0f2f4}td:last-child,th:last-child{box-shadow:-3px 0 4px #0000000a;border-left:1px solid #dce0e4}
tbody tr:nth-child(even) td{background:#fafbfc}tbody tr:hover td{background:#f0f2f4}tbody tr.selected td{background:#f3eaf1}.entity{gap:0}.entity-mark,.entity small,.compact .entity-mark{display:none}.entity-name{margin:0;font-size:12px;font-weight:500}.pill{font-size:11px;padding:0 5px;border-radius:2px;line-height:19px}.tag{background:none;padding:0;font-size:12px;color:#60666e}.date{font-size:12px}.subline{display:inline;font-size:10px;margin-left:6px}.mono{color:#69727d;font-size:11px}.muted{color:#7c838c}.row-action{padding:0 5px!important;height:23px!important}.pagination{height:35px;min-height:35px;flex-shrink:0;padding:3px 9px;background:#f7f8f9;font-size:11px}.pagination button,.pagination select{height:24px}.pagination-controls{gap:6px}.current-page{padding:2px 8px}.statusbar{height:23px;min-height:23px;align-items:center;padding:0 5px;font-size:10px} tbody tr:nth-child(even) td{background:#fafbfc}tbody tr:hover td{background:#f0f2f4}tbody tr.selected td{background:#f3eaf1}.entity{gap:0}.entity-mark,.entity small,.compact .entity-mark{display:none}.entity-name{margin:0;font-size:12px;font-weight:500}.pill{font-size:11px;padding:0 5px;border-radius:2px;line-height:19px}.tag{background:none;padding:0;font-size:12px;color:#60666e}.date{font-size:12px}.subline{display:inline;font-size:10px;margin-left:6px}.mono{color:#69727d;font-size:11px}.muted{color:#7c838c}.row-action{padding:0 5px!important;height:23px!important}.pagination{height:35px;min-height:35px;flex-shrink:0;padding:3px 9px;background:#f7f8f9;font-size:11px}.pagination button,.pagination select{height:24px}.pagination-controls{gap:6px}.current-page{padding:2px 8px}.statusbar{height:23px;min-height:23px;align-items:center;padding:0 5px;font-size:10px}
.drawer{margin:auto;width:620px;max-width:90vw;height:auto;max-height:90vh;border-radius:3px}.dialog-head{padding:11px 15px;background:#f5f6f7}.dialog-head h2{font-size:14px}.dialog-head p{font-size:10px;margin-top:2px}.dialog-body{padding:15px;gap:13px}.drawer .dialog-body{display:grid;grid-template-columns:1fr 1fr}.drawer .dialog-body>.help{grid-column:1/-1}.dialog-body input:not([type=checkbox]),.dialog-body select{height:29px}.dialog-body .field{gap:5px}.dialog-footer{padding:9px 15px}.permissions{grid-template-columns:1fr;gap:6px}.columns-dialog{border-radius:3px}.help{border-radius:2px;font-size:11px} .drawer{margin:auto;width:620px;max-width:90vw;height:auto;max-height:90vh;border-radius:3px}.dialog-head{padding:11px 15px;background:#f5f6f7}.dialog-head h2{font-size:14px}.dialog-head p{font-size:10px;margin-top:2px}.dialog-body{padding:15px;gap:13px}.drawer .dialog-body{display:grid;grid-template-columns:1fr 1fr}.drawer .dialog-body>.help{grid-column:1/-1}.dialog-body input:not([type=checkbox]),.dialog-body select{height:29px}.dialog-body .field{gap:5px}.dialog-footer{padding:9px 15px}.permissions{grid-template-columns:1fr;gap:6px}.columns-dialog{border-radius:3px}.help{border-radius:2px;font-size:11px}
/* Desktop window frame and navigation hierarchy. */
.app{grid-template-columns:180px minmax(0,1fr);grid-template-rows:32px minmax(0,1fr);height:100dvh;min-height:594px;border:1px solid #c9c4cd}
.ui-icon{display:block;width:16px;height:16px;flex-shrink:0;fill:none;stroke:currentColor;stroke-width:1.65;stroke-linecap:round;stroke-linejoin:round}
.window-titlebar{grid-column:1/-1;display:flex;align-items:center;justify-content:space-between;background:var(--brand);border-bottom:1px solid var(--brand);user-select:none}.window-caption{display:flex;align-items:center;gap:8px;padding-left:11px;color:#fff;font-size:11px}.window-caption .ui-icon{color:#fff}.window-actions{display:flex;height:31px}.window-actions button{display:grid;place-items:center;width:46px;height:31px;padding:0;border:0;border-radius:0;background:transparent;color:#fff}.window-actions .ui-icon{width:12px;height:12px;stroke-width:1}.window-actions button:hover{background:#ffffff25}.window-actions .window-close:hover{background:#c42b1c;color:#fff}
.sidebar{grid-column:1;grid-row:2;min-height:0;overflow:auto}.shell{grid-column:2;grid-row:2;min-height:0}
.brand{justify-content:center;padding:0;background:#f7f8f9;border-bottom:1px solid #e2e4e8;color:var(--brand)}.brand>.ui-icon{width:32px;height:32px;stroke-width:1.5}
.section-label{display:flex;align-items:center;gap:8px;margin:13px 8px 4px;padding:7px 8px;background:transparent;color:#65516b;font-size:12px;font-weight:650;border-radius:3px;letter-spacing:0}.section-label>.ui-icon{width:17px;height:17px}
.sidebar nav{margin:0 8px 0 16px;border-left:1px solid #ddd6e0;padding-left:5px}.sidebar .nav{height:34px;padding:0 9px;gap:8px;border-radius:3px;font-size:12px;color:#727785}.sidebar .nav.active{padding-left:9px;background:transparent;color:var(--brand-dark);font-weight:650}.sidebar .nav .ui-icon{width:15px;height:15px}.sidebar .nav:hover:not(:disabled){background:transparent;color:var(--brand-dark)}.sidebar .nav.active:after{display:block;content:"";height:14px;width:2px;border-radius:1px;background:var(--brand);margin-left:auto}
.title-account{display:flex;align-items:center;gap:12px;margin-left:auto;padding:0 18px;color:#fff;font-size:10px}
.title-account b{font-weight:600;color:#fff}
.account-divider{height:11px;border-left:1px solid #ffffff40}
</style> </style>
</head> </head>
<body> <body>
<div class="app"> <div class="app"><div class="window-titlebar"><div class="window-caption"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="m12 2 9 5v10l-9 5-9-5V7zM3 7l9 5 9-5M12 12v10M7.5 4.5l9 5V14"/></svg><span>29 供应链 — 运营管理工作台</span></div><div class="title-account"><span>积分 <b>9,759</b></span><span class="account-divider"></span><span>管理员</span></div><div class="window-actions" aria-label="窗口按钮外观演示"><button type="button" class="" aria-label="最小化(外观演示)" title="最小化 · 仅外观演示"><svg class="ui-icon" viewBox="0 0 12 12" aria-hidden="true"><path d="M1 6h10"/></svg></button><button type="button" class="" aria-label="最大化(外观演示)" title="最大化 · 仅外观演示"><svg class="ui-icon" viewBox="0 0 12 12" aria-hidden="true"><path d="M1.5 1.5h9v9h-9z"/></svg></button><button type="button" class="window-close" aria-label="关闭(外观演示)" title="关闭 · 仅外观演示"><svg class="ui-icon" viewBox="0 0 12 12" aria-hidden="true"><path d="m1.5 1.5 9 9m0-9-9 9"/></svg></button></div></div>
<aside class="sidebar"><div class="brand"><b>29</b><div><strong>供应链</strong><small>COMMERCE WORKSPACE</small></div></div><div class="section-label">店铺工作台</div><nav aria-label="店铺工作台"><button class="nav active" data-page="stores"><span class="nav-index">01</span>店铺管理</button><button class="nav" data-page="accounts"><span class="nav-index">02</span>子账号管理</button></nav><div class="section-label">超级管理</div><nav aria-label="超级管理"><button class="nav" data-page="superstores"><span class="nav-index">03</span>超级店铺管理</button><button class="nav" data-page="users"><span class="nav-index">04</span>超级用户管理</button><button class="nav" data-page="oem"><span class="nav-index">05</span>OEM 贴牌管理</button></nav><div class="sidebar-bottom"><span class="demo-badge">桌面工作台 · 演示</span><p>专注每一家店铺的日常运营<br>本地交互演示 · 数据均为模拟</p><button class="text" id="designNotes">界面设计说明</button></div></aside> <aside class="sidebar"><div class="brand" aria-label="29 供应链"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="m12 2 9 5v10l-9 5-9-5V7zM3 7l9 5 9-5M12 12v10M7.5 4.5l9 5V14"/></svg></div><div class="section-label"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 10v11h18V10M2 10l2-7h16l2 7zM9 21v-7h6v7M7 3v7M17 3v7"/></svg><span>店铺工作台</span></div><nav aria-label="店铺工作台"><button class="nav active" data-page="stores"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 10v11h18V10M2 10l2-7h16l2 7zM9 21v-7h6v7M7 3v7M17 3v7"/></svg>店铺管理</button><button class="nav" data-page="accounts"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M16 21v-3a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v3M9 10a4 4 0 1 0 0-8 4 4 0 0 0 0 8M18 3a4 4 0 0 1 0 8M22 21v-3a4 4 0 0 0-3-4"/></svg>子账号管理</button></nav><div class="section-label"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2l9 4v6c0 5-9 10-9 10S3 17 3 12V6zM8 12l3 3 5-6"/></svg><span>超级管理</span></div><nav aria-label="超级管理"><button class="nav" data-page="superstores"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 10v11h18V10M2 10l2-7h16l2 7zM9 21v-7h6v7M7 3v7M17 3v7"/></svg>超级店铺管理</button><button class="nav" data-page="users"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M16 21v-3a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v3M9 10a4 4 0 1 0 0-8 4 4 0 0 0 0 8M18 3a4 4 0 0 1 0 8M22 21v-3a4 4 0 0 0-3-4"/></svg>超级用户管理</button><button class="nav" data-page="oem"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 3h10l7 7-11 11-7-7V4zM8 7h.01"/></svg>OEM 贴牌管理</button></nav><div class="sidebar-bottom"><span class="demo-badge">桌面工作台 · 演示</span><p>专注每一家店铺的日常运营<br>本地交互演示 · 数据均为模拟</p><button class="text" id="designNotes">界面设计说明</button></div></aside>
<div class="shell"><header class="topbar"><div class="breadcrumb">管理工作空间 <span>/</span><span id="crumb">店铺管理</span></div><div class="profile"><span>账户积分 <b>9,759</b></span><span class="avatar">管</span><span>管理员</span></div></header> <div class="shell"><span id="crumb" hidden></span>
<main class="content"><section class="page-heading"><div><div class="eyebrow" id="eyebrow">STORE MANAGEMENT</div><h1 id="pageTitle">店铺管理</h1><p id="pageDescription"></p></div><div class="heading-actions"><button id="refresh">刷新列表</button><button class="primary" id="add">添加店铺</button></div></section> <main class="content"><section class="page-heading"><div><div class="eyebrow" id="eyebrow">STORE MANAGEMENT</div><h1 id="pageTitle">店铺管理</h1><p id="pageDescription"></p></div><div class="heading-actions"><button id="refresh">刷新列表</button><button class="primary" id="add">添加店铺</button></div></section>
<section class="workspace" aria-label="管理列表"><div class="tabs" id="tabs"></div><form class="filters" id="filterForm"><div class="field search-field"><label for="keyword">关键词</label><input id="keyword" maxlength="100" placeholder="搜索店铺名称 / 店铺 ID"></div><div class="field"><label for="groupFilter">所属分组</label><select id="groupFilter"></select></div><div class="field"><label for="statusFilter">状态</label><select id="statusFilter"><option value="">全部状态</option><option>正常</option><option>即将到期</option><option>已过期</option></select></div><button class="primary" type="submit">查询</button><button type="button" id="reset">重置</button></form> <section class="workspace" aria-label="管理列表"><div class="tabs" id="tabs"></div><form class="filters" id="filterForm"><div class="field search-field"><label for="keyword">关键词</label><input id="keyword" maxlength="100" placeholder="搜索店铺名称 / 店铺 ID"></div><div class="field"><label for="groupFilter">所属分组</label><select id="groupFilter"></select></div><div class="field"><label for="statusFilter">状态</label><select id="statusFilter"><option value="">全部状态</option><option>正常</option><option>即将到期</option><option>已过期</option></select></div><button class="primary" type="submit">查询</button><button type="button" id="reset">重置</button></form>
+58
View File
@@ -0,0 +1,58 @@
const fs = require('node:fs');
const vm = require('node:vm');
const assert = require('node:assert/strict');
const html = fs.readFileSync(__dirname + '/index.html', 'utf8');
const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
const elements = new Map();
function element(id) {
if (!elements.has(id)) elements.set(id, { value: id === 'pageSize' ? '50' : '', innerHTML: '', textContent: '', classList: { toggle() { return true; } }, setAttribute() {}, showModal() {}, close() {} });
return elements.get(id);
}
const context = vm.createContext({ document: { getElementById: element, querySelectorAll: () => [] }, console: { assert: assert.ok }, setTimeout: () => 1, clearTimeout() {}, FormData, assert });
vm.runInContext(script, context);
vm.runInContext(`
assert.equal(visibleRows().length, 50);
page=2; assert.equal(visibleRows().length, 22);
query='乐乐'; assert.equal(filtered().length, 3);
query=''; group='服饰鞋包'; assert.equal(filtered().length, 24);
group=''; tab='已过期'; assert.ok(filtered().every(r=>r.status==='已过期'));
for (const key of Object.keys(configs)) {
switchPage(key);
assert.ok($('tbody').innerHTML.includes('data-edit'));
openEditor(data[key][0].id);
assert.ok($('editorFields').innerHTML.includes('name="name"'));
hiddenColumns.add('group'); renderTable();
assert.ok(!$('thead').innerHTML.includes('所属分组'));
}
switchPage('stores');
assert.equal(configs.stores.columns.length, 11);
assert.equal(configs.users.columns.length, 13);
assert.ok($('tbody').innerHTML.includes('data-store-action'));
selected.add(data.stores[3].id); $('login').onclick();
assert.equal(data.stores[3].login, '登录成功');
$('batch').onclick();
assert.equal(data.stores[3].status, '正常');
assert.equal(selected.size, 0);
query='no-matching-record'; renderTable();
assert.ok($('tbody').innerHTML.includes('没有匹配的记录'));
assert.equal($('next').disabled, true);
assert.equal(escapeHtml('<img onerror="bad">'), '&lt;img onerror=&quot;bad&quot;&gt;');
`, context);
console.log('PASS: script syntax, five page renders, pagination, filters, editors, columns, batch action, empty state and HTML escaping.');
// Verify contextual navigation against the actual HTML attributes.
const markup = html.split("<script>")[0];
const ids = [...markup.matchAll(/\bid="([^"]+)"/g)].map(m => m[1]);
assert.equal(ids.length, new Set(ids).size);
const modules = [...markup.matchAll(/data-module="([^"]+)" data-start="([^"]+)"/g)].map(m => ({ dataset: { module: m[1], start: m[2] }, classList: { toggle() {} }, setAttribute(name, value) { this[name] = value; } }));
const pages = [...markup.matchAll(/data-area="([^"]+)" data-page="([^"]+)"/g)].map(m => ({ dataset: { area: m[1], page: m[2] }, classList: { toggle() {} }, setAttribute() {} }));
context.document.querySelectorAll = selector => selector === "[data-module]" ? modules : pages;
assert.equal(modules.length, 3); assert.equal(pages.length, 5);
for (const page of pages) {
vm.runInContext("switchPage(" + JSON.stringify(page.dataset.page) + ")", context);
assert.equal(page.hidden, false);
assert.ok(pages.every(p => p.hidden === (p.dataset.area !== page.dataset.area)));
assert.equal(modules.filter(m => m["aria-pressed"]).length, 1);
assert.equal(modules.find(m => m["aria-pressed"]).dataset.module, page.dataset.area);
}
console.log("PASS: three icon modules, five contextual pages, active and hidden navigation states.");
+253
View File
@@ -0,0 +1,253 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>29 供应链 · 桌面工作台 Demo 2</title>
<style>
:root{--brand:#98638f;--brand-dark:#784b70;--tint:#f3ebf2;--ink:#353a44;--muted:#9299a4;--line:#e0e4e9;--canvas:#f4f5f7;--green:#3b876e;--red:#bc626b;--amber:#aa7b35}
*{box-sizing:border-box}
body{margin:0;min-width:1040px;font:12px/1.5 "Segoe UI","Microsoft YaHei",sans-serif;color:var(--ink);background:var(--canvas)}
button,input,select{font:inherit;color:inherit}
button{cursor:pointer;white-space:nowrap;height:28px;padding:0 10px;background:white;border:1px solid #d8dde4;border-radius:4px}
button:hover:not(:disabled){background:#f2f4f7;border-color:#bcc4ce}
button:disabled{color:#abb2bc;cursor:default}
button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid #98638f;outline-offset:2px}
button.primary{background:var(--brand);color:white;border-color:transparent}
button.primary:hover:not(:disabled){background:var(--brand-dark);border-color:transparent}
input,select{height:28px;padding:0 8px;border:1px solid #d8dde4;border-radius:4px;background:white;min-width:0}
input[type=checkbox]{width:13px;height:13px;margin:0;vertical-align:middle;accent-color:var(--brand);cursor:pointer}
[hidden]{display:none!important}
svg{display:block;width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
.sprite{position:absolute;width:0;height:0;overflow:hidden}
.app{height:100dvh;min-height:580px;display:grid;grid-template-rows:32px 60px minmax(0,1fr)}
.window-titlebar{display:flex;align-items:center;justify-content:space-between;background:#f5f3f6;border-bottom:1px solid #e8e4ea;user-select:none}
.window-caption{display:flex;align-items:center;gap:8px;padding-left:12px;font-size:11px;color:#77717c}
.window-caption svg{width:16px;height:16px;color:var(--brand)}
.window-actions{display:flex;height:32px}
.window-actions button{display:grid;place-items:center;width:46px;height:32px;padding:0;border:0;border-radius:0;background:transparent;color:#55525b}
.window-actions button svg{width:12px;height:12px;stroke-width:1}
.window-actions button:hover{background:#e7e4e9;border:0}
.window-actions .window-close:hover{background:#c42b1c;color:#fff}
.app-header{display:flex;align-items:stretch;background:#fff;border-bottom:1px solid #e5e3e9}
.brand{width:180px;min-width:180px;display:flex;align-items:center;gap:10px;padding:0 18px;background:#faf8fb}
.brand-mark{height:34px;width:34px;display:grid;place-items:center;color:var(--brand);flex-shrink:0}
.brand-mark svg{width:32px;height:32px;stroke-width:1.35}
.brand strong{display:block;font-size:16px;font-weight:650;letter-spacing:.5px;color:#60445c}
.brand small{display:none}
.modulebar{display:flex;gap:8px;align-items:center;padding:0 16px}
.module{display:flex;align-items:center;gap:9px;height:40px;padding:0 16px;border:1px solid transparent;border-radius:6px;background:transparent;color:#788191;font-size:12px}
.module svg{width:21px;height:21px}
.module:hover:not(:disabled){background:#f4f3f7;border-color:transparent}
.module.active{color:var(--brand-dark);background:#eee5ed;font-weight:600}
.account{display:flex;align-items:center;gap:15px;margin-left:auto;padding:0 18px;font-size:11px;color:#8a929e}
.account b{font-weight:600;color:#746071}
.account .avatar{display:grid;place-items:center;width:27px;height:27px;background:#eee8ef;color:#8e6e89;border-radius:50%;font-size:11px}
.account button{background:transparent;border:0;color:#8a929e;padding:0 2px;font-size:11px}
.desktop-body{display:grid;grid-template-columns:180px minmax(0,1fr);min-height:0}
.function-panel{display:flex;flex-direction:column;background:#faf8fb;border-right:1px solid #e7e3e9;padding:16px 10px 12px}
.panel-heading{display:flex;justify-content:space-between;align-items:center;padding:0 10px 16px;color:#929aa7;font-size:11px}
.panel-heading b{font-weight:500}
.panel-heading span{font-size:10px;color:#a49aa9;letter-spacing:1px}
.nav{display:flex;align-items:center;gap:10px;text-align:left;width:100%;height:35px;margin-bottom:5px;border:0;background:transparent;border-radius:5px;padding:0 11px;color:#6c7685}
.nav svg{width:16px;height:16px}
.nav.active{background:#eee5ed;color:var(--brand-dark);font-weight:600}
.nav.active:after{content:"";width:5px;height:5px;border-right:1px solid currentColor;border-top:1px solid currentColor;transform:rotate(45deg);margin-left:auto;opacity:.6}
.panel-bottom{margin-top:auto;padding:12px 10px 0;border-top:1px solid #e6e9ee;color:#91a095;font-size:10px}
.panel-bottom small{display:block;color:#a8afb9;font-size:9px;margin-top:4px}
.shell{display:flex;min-width:0;min-height:0}
.content{display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;padding:0 12px}
.page-heading{height:44px;min-height:44px;display:flex;align-items:center;gap:12px;padding:0 1px}
h1{font-size:14px;font-weight:600;margin:0}
.page-heading p{display:none}
.workspace{display:flex;flex-direction:column;flex:1;min-height:0;background:#fff;border:1px solid #dce1e7;border-radius:5px;overflow:hidden}
.toolbar{display:flex;align-items:center;gap:9px;min-height:43px;padding:7px 10px;border-bottom:1px solid #e6e9ee}
.command-group{display:flex;gap:5px;align-items:center;padding-right:9px;border-right:1px solid #e6e9ee}
.command-group:last-child{border:0;margin-left:auto;padding:0}
.toolbar button{display:flex;align-items:center;gap:6px;font-size:11px;border-color:transparent;background:transparent;padding:0 8px}
.toolbar button.primary{background:var(--brand);color:white;padding:0 10px}
.toolbar button:before{content:"";height:15px;width:15px;background:currentColor;mask:var(--icon) center/contain no-repeat}
.filters{display:flex;align-items:center;gap:10px;min-height:44px;margin:0;padding:7px 10px;background:#fcfcfd;border-bottom:1px solid #e8ebef;flex-wrap:wrap}
.field{display:flex;flex-direction:column;gap:5px}
.filters .field{flex-direction:row;align-items:center;gap:7px}
.field label{font-size:11px;color:#89929f;white-space:nowrap}
.search-field input{width:230px}
.filters select{width:105px}
.filters button{font-size:11px}
.list-header{min-height:35px;height:35px;display:flex;align-items:center;justify-content:space-between;padding:0 11px;gap:8px}
.tabs{display:flex;align-items:stretch;height:35px;gap:18px}
.tab{height:35px;border:0;padding:0;background:transparent;border-radius:0;color:#9199a5;font-size:11px;position:relative}
.tab.active{color:var(--brand-dark);font-weight:600}
.tab.active:after{content:"";position:absolute;bottom:0;left:0;right:0;background:var(--brand);height:2px}
.tab small{font-size:10px;margin-left:6px;background:#f2f4f6;border-radius:3px;padding:0 4px}
.selection-info{display:flex;gap:10px;align-items:center;font-size:10px;white-space:nowrap}
.selection-info>span+span{padding-left:10px;border-left:1px solid #e5e8ed}
.selection{color:var(--brand-dark)}
.muted{color:var(--muted)}
.table-scroll{flex:1;min-height:100px;overflow:auto;border-top:1px solid #dce1e7}
table{border-collapse:separate;border-spacing:0;width:max-content;min-width:100%;font-size:12px;white-space:nowrap}
th{text-align:left;position:sticky;top:0;z-index:2;background:#f1f3f6;font-weight:500;color:#66717f;height:30px;border-right:1px solid #e0e5eb;border-bottom:1px solid #d9dfe6;padding:0 10px}
td{height:36px;padding:2px 10px;border-bottom:1px solid #edf0f3;border-right:1px solid #edf0f3;background:#fff}
.compact td{height:29px;padding-top:1px;padding-bottom:1px}
tbody tr:nth-child(even) td{background:#fcfcfd}
tbody tr:hover td{background:#f6f3f7}
tbody tr.selected td{background:#f0e6ef}
th:first-child,td:first-child{width:31px;min-width:31px;text-align:center;padding:0 8px;position:sticky;left:0;z-index:1}
th:first-child{z-index:3}
th:last-child,td:last-child{position:sticky;right:0;border-left:1px solid #dfe4ea;box-shadow:-3px 0 5px #00000004}
th:last-child{z-index:3}
.row-number{text-align:right;color:#9ba4b0;font-size:11px}
.entity-mark,.entity small{display:none}
.entity-name{font-weight:400}
.mono{font:11px Consolas,monospace;color:#838d9c}
.date{font-size:11px;color:#778291;font-variant-numeric:tabular-nums}
.subline{display:inline;font-size:10px;margin-left:5px}
.pill{font-size:10px;color:var(--green);background:#edf6f1;display:inline-flex;gap:5px;align-items:center;padding:1px 5px;border-radius:3px}
.pill:before{content:"";width:4px;height:4px;background:currentColor;border-radius:50%}
.pill.warn{color:var(--amber);background:#faf3e9}
.pill.error{color:var(--red);background:#fbefef}
.tag{color:#7e8794;font-size:11px}
button.text{background:transparent;border:0;color:#7c6a7b;padding:0 5px;height:24px;font-size:11px}
.sort{border:0;background:transparent;padding:0;height:auto;color:inherit;font:inherit}
.empty{text-align:center;height:150px!important;color:var(--muted)}
.pagination{height:36px;min-height:36px;display:flex;justify-content:space-between;align-items:center;padding:0 10px;border-top:1px solid #dfe4ea;background:#fcfcfd;font-size:10px;color:#959daa}
.pagination-controls{display:flex;align-items:center;gap:6px}
.pagination button,.pagination select{height:24px;font-size:11px}
.current-page{padding:2px 7px;background:var(--tint);color:var(--brand-dark);border-radius:3px}
.statusbar{height:23px;min-height:23px;display:flex;align-items:center;justify-content:space-between;font-size:9px;color:#a4abb5;padding:0 1px}
dialog{border:1px solid #dce1e7;border-radius:7px;padding:0;color:var(--ink);box-shadow:0 18px 70px #30233330;max-width:90vw;max-height:90vh}
dialog::backdrop{background:#20232c45}
.drawer{width:620px}
.dialog-head{padding:12px 16px;background:#fafbfc;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between}
.dialog-head h2{font-size:14px;margin:0}
.dialog-head p{font-size:10px;color:var(--muted);margin:3px 0 0}
.dialog-body{padding:16px;display:flex;flex-direction:column;gap:13px}
.drawer .dialog-body{display:grid;grid-template-columns:1fr 1fr}
.dialog-body input:not([type=checkbox]),.dialog-body select{width:100%;height:30px}
.dialog-footer{padding:10px 16px;display:flex;justify-content:flex-end;gap:8px;border-top:1px solid var(--line)}
.help{grid-column:1/-1;background:var(--canvas);color:var(--muted);padding:10px;font-size:11px}
.permissions{display:grid;gap:7px;font-size:11px}
.permissions label,.columns-dialog label{display:flex;align-items:center;gap:8px}
.columns-dialog{width:330px}
.notice{padding:10px;background:var(--tint);color:var(--brand-dark);border-radius:4px}
.toast{position:fixed;z-index:10;bottom:35px;left:50%;transform:translateX(-50%);padding:10px 18px;background:#4a3c49;color:white;border-radius:5px;box-shadow:0 5px 20px #0002}
@media(max-width:1180px){.account{gap:10px;padding:0 12px}.account .points{display:none}.module{padding:0 13px}.page-heading p{display:none}.content{padding:0 8px}.toolbar{gap:5px}.command-group{gap:3px;padding-right:5px}.toolbar button{padding:0 6px}.search-field input{width:190px}.filters{gap:8px}.selection-info #resultCount{display:none}}
#add{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M12%205v14M5%2012h14%22%2F%3E%3C%2Fsvg%3E")}
#refresh{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M20%207v5h-5M4%2017v-5h5M5%207a8%208%200%200%201%2014-1l1%206M4%2012l1%206a8%208%200%200%200%2014-1%22%2F%3E%3C%2Fsvg%3E")}
#batch{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M8%203h13v14H8zM3%208v13h13M11%207h7M11%2011h7%22%2F%3E%3C%2Fsvg%3E")}
#detect{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M4%2012l5%205L20%206%22%2F%3E%3C%2Fsvg%3E")}
#login{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M14%203h7v18h-7M3%2012h13M11%207l5%205-5%205%22%2F%3E%3C%2Fsvg%3E")}
#density{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M3%205h18M3%2012h18M3%2019h18%22%2F%3E%3C%2Fsvg%3E")}
#columnSettings{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M3%204h18v16H3zM9%204v16M15%204v16%22%2F%3E%3C%2Fsvg%3E")}
</style>
</head>
<body>
<svg class="sprite" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"><defs>
<symbol id="i-box" viewBox="0 0 24 24"><path d="m12 2 9 5v10l-9 5-9-5V7zM3 7l9 5 9-5M12 12v10M7.5 4.5l9 5V14"/></symbol>
<symbol id="i-shop" viewBox="0 0 24 24"><path d="M3 10v11h18V10M2 10l2-7h16l2 7zM9 21v-7h6v7M7 3v7M17 3v7"/></symbol>
<symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 2l9 4v6c0 5-9 10-9 10S3 17 3 12V6zM8 12l3 3 5-6"/></symbol>
<symbol id="i-brand" viewBox="0 0 24 24"><path d="M4 3h10l7 7-11 11-7-7V4zM8 7h.01"/></symbol>
<symbol id="i-people" viewBox="0 0 24 24"><path d="M16 21v-3a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v3M9 10a4 4 0 1 0 0-8 4 4 0 0 0 0 8M18 3a4 4 0 0 1 0 8M22 21v-3a4 4 0 0 0-3-4"/></symbol>
</defs></svg>
<div class="app">
<div class="window-titlebar">
<div class="window-caption"><svg aria-hidden="true"><use href="#i-box"/></svg><span>29 供应链</span></div>
<div class="window-actions" aria-label="窗口按钮外观演示">
<button type="button" aria-label="最小化(外观演示)" title="最小化 · 仅外观演示"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1 6h10"/></svg></button>
<button type="button" aria-label="最大化(外观演示)" title="最大化 · 仅外观演示"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1.5 1.5h9v9h-9z"/></svg></button>
<button type="button" class="window-close" aria-label="关闭(外观演示)" title="关闭 · 仅外观演示"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="m1.5 1.5 9 9m0-9-9 9"/></svg></button>
</div>
</div>
<header class="app-header">
<div class="brand"><span class="brand-mark"><svg aria-hidden="true"><use href="#i-box"/></svg></span><div><strong>29 供应链</strong></div></div>
<nav class="modulebar" aria-label="业务模块">
<button class="module" data-module="operation" data-start="stores"><svg aria-hidden="true"><use href="#i-shop"/></svg>店铺运营</button>
<button class="module" data-module="admin" data-start="users"><svg aria-hidden="true"><use href="#i-shield"/></svg>超级管理</button>
<button class="module" data-module="brand" data-start="oem"><svg aria-hidden="true"><use href="#i-brand"/></svg>品牌管理</button>
</nav>
<div class="account"><span class="points">账户积分 <b>9,759</b></span><button id="designNotes">布局说明</button><span class="avatar" aria-hidden="true">管</span><span>管理员</span></div>
</header>
<div class="desktop-body">
<aside class="function-panel" aria-label="模块内功能">
<div class="panel-heading"><span>工作区</span><b id="moduleTitle" hidden>店铺运营</b></div>
<button class="nav" data-area="operation" data-page="stores"><svg aria-hidden="true"><use href="#i-shop"/></svg><span>店铺管理</span></button>
<button class="nav" data-area="operation" data-page="accounts"><svg aria-hidden="true"><use href="#i-people"/></svg><span>子账号管理</span></button>
<button class="nav" data-area="admin" data-page="superstores"><svg aria-hidden="true"><use href="#i-shop"/></svg><span>超级店铺</span></button>
<button class="nav" data-area="admin" data-page="users"><svg aria-hidden="true"><use href="#i-people"/></svg><span>超级用户</span></button>
<button class="nav" data-area="brand" data-page="oem"><svg aria-hidden="true"><use href="#i-brand"/></svg><span>OEM 贴牌</span></button>
<div class="panel-bottom">● 本地演示环境<small>数据仅在本次浏览中生效</small></div>
</aside>
<div class="shell"><main class="content">
<section class="page-heading"><h1 id="pageTitle">店铺管理</h1><p id="pageDescription"></p><span id="crumb" hidden></span><span id="eyebrow" hidden></span></section>
<section class="workspace" aria-label="管理列表">
<div class="toolbar" aria-label="当前页面操作">
<div class="command-group" role="group" aria-label="记录操作"><button class="primary" id="add">添加店铺</button><button id="refresh">刷新列表</button></div>
<div class="command-group" role="group" aria-label="选中记录操作"><button id="batch" disabled>批量续期</button><button id="detect" disabled>检测选中</button><button id="login" disabled>登录选中</button></div>
<div class="command-group" role="group" aria-label="表格视图"><button id="density" aria-pressed="true">舒适视图</button><button id="columnSettings">列设置</button></div>
</div>
<form class="filters" id="filterForm">
<div class="field search-field"><label for="keyword">关键词</label><input id="keyword" maxlength="100" placeholder="搜索店铺名称 / 店铺 ID"></div>
<div class="field"><label for="groupFilter">分组</label><select id="groupFilter"></select></div>
<div class="field"><label for="statusFilter">状态</label><select id="statusFilter"><option value="">全部状态</option></select></div>
<button class="primary" type="submit">查询</button><button type="button" id="reset">重置</button>
</form>
<div class="list-header"><div class="tabs" id="tabs"></div><div class="selection-info"><span id="selection" class="muted">选择记录后可批量操作</span><span id="resultCount" class="muted"></span></div></div>
<div class="table-scroll"><table id="table" class="compact"><thead id="thead"></thead><tbody id="tbody"></tbody></table></div>
<footer class="pagination"><span id="range"></span><div class="pagination-controls"><label for="pageSize">每页</label><select id="pageSize"><option>20</option><option selected>50</option><option>100</option></select><button id="prev" aria-label="上一页">上一页</button><span class="current-page" id="pageNumber">1</span><button id="next" aria-label="下一页">下一页</button></div></footer>
</section>
<footer class="statusbar"><span id="loadStatus">数据已就绪 · 本地演示</span><span>Demo 2 · 桌面工作台</span></footer>
</main></div></div></div>
<dialog class="drawer" id="editor"><form id="editForm"><header class="dialog-head"><div><h2 id="editorTitle"></h2><p>修改仅在本次演示中生效</p></div><button type="button" class="text" data-close="editor">关闭</button></header><div class="dialog-body" id="editorFields"></div><footer class="dialog-footer"><button type="button" data-close="editor">取消</button><button class="primary" type="submit">保存</button></footer></form></dialog>
<dialog class="columns-dialog" id="columns"><header class="dialog-head"><h2>显示的列</h2><button class="text" data-close="columns">完成</button></header><div class="dialog-body" id="columnOptions"></div></dialog>
<dialog id="details" style="width:520px;max-width:95vw"><header class="dialog-head"><h2 id="detailTitle"></h2><button class="text" data-close="details">关闭</button></header><div class="dialog-body" id="detailBody"></div></dialog><div class="toast" role="status" id="toast" hidden></div>
<script>
'use strict';
const $=id=>document.getElementById(id);
const escapeHtml=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const names=['乐乐生活馆','清麦日用百货','栖木家居旗舰店','佐薇服饰小铺','青禾优选','云朵母婴生活','拾光好物集合店','橙意食品专营店','木子家居日用','浅湾服饰店','山野户外生活','简物生活旗舰店','暖晨家纺店','知味食品小铺','白露日用百货','云间服饰集合店','小满优选','春序家居店','鹿鸣母婴店','青山好物','星野百货','暮色生活馆','沐光服饰','初禾日用品'];
const stores=Array.from({length:72},(_,i)=>({name:names[i%names.length]+(i>=24?" · "+(Math.floor(i/24)+1)+"店":""),i})).map(({name,i})=>({id:1001+i,name,code:'wx'+(316129135100+i*74031).toString(16)+'a'+i,group:['精选店铺','服饰鞋包','生活百货'][i%3],account:['运营一组','运营二组','未分配'][i%3],owner:'demo_owner_'+(i%4+1),phone:'138****'+String(1200+i),status:i%7===3?'已过期':i%5===2?'即将到期':'正常',expires:i%7===3?'2026-10-20':i%5===2?'2026-11-02':'2027-05-09',note:i%3===0?'重点运营店铺':'',permissions:['店铺列表','订单管理'],created:'2026-08-14 15:16',login:i%7===3?'未登录':'登录成功',api:i%4===0?'未购买':'已开通',permanent:i%9===0?'是':'否',secondary:i%6===0?'已启用':'未启用'}));
const data={stores,superstores:stores.map(r=>({...r,id:r.id+3000})),accounts:['林小夏','陈晓','周宁','许安','李可','宋悦'].map((name,i)=>({id:2001+i,name,code:'operator_'+(i+1),phone:'139****'+(2300+i),group:['运营','客服','仓储'][i%3],status:i===4?'已停用':'正常',account:'主账号 · 演示企业',note:'',permissions:['店铺列表','订单管理']})),users:Array.from({length:18},(_,i)=>({id:3001+i,name:['青禾供应链','云飞商贸','开兴科技','花下海','众店联源','微擎科技'][i%6]+(i>5?' '+(Math.floor(i/6)+1):''),code:'user_'+(801+i),phone:'137****'+(5600+i),group:i%4===0?'代理商':'主账户',status:i===5?'已停用':'正常',company:['青禾商贸有限公司','云飞供应链有限公司','开兴网络科技'][i%3],points:300+i*20,balance:(140+i*37.5).toFixed(2),fee:'2.50',monthly:30,returnFee:'3.00',agent:['云飞','大牛','花下海'][i%3],type:'普通用户',permissions:['商品采集','在线寄件'],note:''})),oem:['桃花源供应链','店速通','开茂科技','枫谷拍单','洋总代理','臻和网络','贝塔一体仓','佳俊商贸'].map((name,i)=>({id:5001+i,name,code:'26'+(701+i)+'TW'+i,group:'品牌合作',status:'正常',account:'demo_brand_'+(i+1),phone:'136****'+(7400+i),note:'',permissions:[]}))};
const configs={stores:{title:'店铺管理',en:'STORE MANAGEMENT',desc:'集中管理店铺、账号与授权,让日常运营井然有序。',add:'添加店铺',batch:'批量续期',search:'搜索店铺名称 / 店铺 ID',columns:[['name','店铺信息'],['group','所属分组'],['account','子账号'],['status','授权状态'],['expires','到期时间'],['note','备注']],groups:['精选店铺','服饰鞋包','生活百货']},superstores:{title:'超级店铺管理',en:'STORE ADMINISTRATION',desc:'跨账号查看全部店铺,统一管理店铺归属与授权状态。',add:'添加店铺',batch:'批量检测',search:'搜索店铺 / 所属账号 / 店铺 ID',columns:[['name','店铺信息'],['owner','所属账号'],['group','店铺分组'],['account','子账号'],['status','授权状态'],['expires','到期时间']],groups:['精选店铺','服饰鞋包','生活百货']},accounts:{title:'子账号管理',en:'TEAM & ACCESS',desc:'为团队分配独立账号,以清晰的访问权限协同管理店铺。',add:'添加子账号',batch:'批量启用',search:'搜索昵称 / 登录账号',columns:[['name','用户信息'],['phone','登录手机号'],['group','角色分组'],['status','账号状态'],['permissions','可访问页面'],['account','所属主账号']],groups:['运营','客服','仓储']},users:{title:'超级用户管理',en:'USER ADMINISTRATION',desc:'统一管理用户、功能权限与账户信息。',add:'添加用户',batch:'批量启用',search:'搜索用户 / 手机号 / 公司',columns:[['name','用户信息'],['group','用户分组'],['company','公司'],['points','积分'],['balance','快递余额'],['fee','每单快递费'],['status','账号状态']],groups:['主账户','代理商']},oem:{title:'OEM 贴牌管理',en:'BRAND PARTNERS',desc:'管理合作品牌标识与主体账号,建立统一的品牌工作空间。',add:'添加贴牌',batch:'批量启用',search:'搜索贴牌名称 / 贴牌编码',columns:[['name','贴牌名称'],['code','贴牌编码'],['account','主体账号'],['status','状态'],['assets','品牌素材']],groups:['品牌合作']}};
configs.stores.columns=[['name','店铺名称'],['code','店铺 ID'],['created','添加时间'],['expires','到期时间'],['status','授权状态'],['group','分组'],['account','子账号'],['phone','子账号手机号'],['login','登录状态'],['api','API 购买'],['note','备注']];
configs.superstores.columns=[['name','店铺名称'],['code','店铺 ID / 登录号码'],['owner','所属账号'],['account','子账号'],['group','店铺分组'],['login','登录状态'],['status','授权状态'],['api','API 购买'],['secondary','二级超管'],['permanent','永久'],['note','备注']];
configs.accounts.columns=[['name','用户昵称'],['code','登录账号'],['phone','手机号'],['group','分组'],['account','所属主账号'],['status','状态'],['permissions','可访问页面'],['note','备注']];
configs.users.columns=[['name','用户昵称'],['phone','手机 / 登录账号'],['group','分组'],['company','公司'],['type','账户类型'],['permissions','功能权限'],['agent','代理名称'],['points','积分'],['monthly','月费耗点'],['balance','快递余额'],['fee','每单快递费'],['returnFee','每单退货费'],['status','状态']];
configs.oem.columns=[['code','贴牌编码'],['name','贴牌名称'],['account','主体账号'],['assets','图标'],['assetsTitle','题图'],['status','状态'],['note','备注']];
let current='stores',tab='',page=1,query='',group='',status='',sortAsc=true,editingId=null,selected=new Set(),hiddenColumns=new Set(),toastTimer;
function isStore(){return current==='stores'||current==='superstores'}
function filtered(){return data[current].filter(r=>(!query||Object.values(r).join(' ').toLowerCase().includes(query))&&(!group||r.group===group)&&(!status||r.status===status)&&(!tab||r.status===tab)).sort((a,b)=>sortAsc?a.name.localeCompare(b.name,'zh-CN'):b.name.localeCompare(a.name,'zh-CN'))}
function visibleRows(){const rows=filtered();return rows.slice((page-1)*Number($('pageSize').value),page*Number($('pageSize').value))}
function showToast(message){$('toast').textContent=message;$('toast').hidden=false;clearTimeout(toastTimer);toastTimer=setTimeout(()=>$('toast').hidden=true,3200)}
function renderTabs(){const tabs=isStore()?[['','全部店铺'],['正常','授权正常'],['即将到期','即将到期'],['已过期','已过期']]:[['','全部'+(current==='oem'?'品牌':'账号')],['正常','正常'],['已停用','已停用']];$('tabs').innerHTML=tabs.map(([value,label])=>`<button class="tab ${tab===value?'active':''}" data-tab="${value}" aria-pressed="${tab===value}">${label}<small>${data[current].filter(r=>!value||r.status===value).length}</small></button>`).join('')}
function cell(r,key){const v=escapeHtml(r[key]);switch(key){case'name':return `<div class="entity"><span class="entity-mark ${r.id%3===0?'alt':''}">${escapeHtml(r.name.slice(0,1))}</span><div><div class="entity-name">${v}</div><small>${escapeHtml(r.code)}</small></div></div>`;case'login':return `<span style="color:${r.login==='登录成功'?'var(--green)':'var(--muted)'}">${v}</span>`;case'status':return `<span class="pill ${r.status==='即将到期'?'warn':r.status==='正常'?'':'error'}">${v==='正常'&&isStore()?'授权正常':v}</span>`;case'group':return `<span class="tag">${v}</span>`;case'expires':return `<span class="date">${v}</span>${r.status==='即将到期'?'<div class="subline" style="color:var(--amber)">5 天后到期</div>':''}`;case'permissions':return `<span class="muted">${escapeHtml(r.permissions.join('、'))||'尚未分配'}</span>`;case'assetsTitle':case'assets':return '<span class="muted">暂未上传</span>';case'balance':case'fee':case'returnFee':return `<span class="date">¥ ${v}</span>`;case'code':case'owner':return `<span class="mono">${v}</span>`;case'note':return `<span class="muted">${v||'—'}</span>`;default:return v||'<span class="muted">—</span>'}}
function renderTable(){const cfg=configs[current],rows=filtered(),size=Number($('pageSize').value);page=Math.max(1,Math.min(page,Math.ceil(rows.length/size)||1));const visible=visibleRows(),cols=cfg.columns.filter(([key])=>!hiddenColumns.has(key));$('thead').innerHTML=`<tr><th><input type="checkbox" id="selectAll" aria-label="选择当前页全部记录" ${visible.length&&visible.every(r=>selected.has(r.id))?'checked':''}></th><th class="row-number">序号</th>${cols.map(([key,label])=>`<th>${key==='name'?`<button class="sort" id="sortName">${label} ${sortAsc?'↑':'↓'}</button>`:label}</th>`).join('')}<th>操作</th></tr>`;$('tbody').innerHTML=visible.length?visible.map((r,index)=>`<tr class="${selected.has(r.id)?'selected':''}"><td><input type="checkbox" data-select="${r.id}" aria-label="选择${escapeHtml(r.name)}" ${selected.has(r.id)?'checked':''}></td><td class="row-number">${(page-1)*size+index+1}</td>${cols.map(([key])=>`<td>${cell(r,key)}</td>`).join('')}<td>${isStore()?`<button class="text row-action" data-store-action="enter" data-id="${r.id}">进入</button><button class="text row-action" data-store-action="renew" data-id="${r.id}">续期</button>`:""}<button class="text row-action" data-detail="${r.id}">${isStore()?'查看':'详情'}</button><button class="text row-action" data-edit="${r.id}">编辑</button></td></tr>`).join(''):`<tr><td class="empty" colspan="${cols.length+3}">没有匹配的记录,请调整筛选条件或重置。</td></tr>`;const all=$('selectAll');all.indeterminate=visible.some(r=>selected.has(r.id))&&!visible.every(r=>selected.has(r.id));$('selection').textContent=selected.size?`已选择 ${selected.size} 项`:'选择记录后可批量操作';$('selection').className=selected.size?'selection':'muted';$('batch').disabled=!selected.size;$('detect').disabled=$('login').disabled=!selected.size;$('resultCount').textContent=`共 ${rows.length} 条记录`;$('range').textContent=rows.length?`显示 ${(page-1)*size+1}–${Math.min(page*size,rows.length)} 条,共 ${rows.length} 条`:'共 0 条记录';$('pageNumber').textContent=`${page} / ${Math.ceil(rows.length/size)||1}`;$('prev').disabled=page===1;$('next').disabled=page*size>=rows.length}
function render(){renderTabs();renderTable()}
function switchPage(key){const area=key==='stores'||key==='accounts'?'operation':key==='oem'?'brand':'admin';document.querySelectorAll('[data-module]').forEach(b=>{b.classList.toggle('active',b.dataset.module===area);b.setAttribute('aria-pressed',b.dataset.module===area)});document.querySelectorAll('[data-area]').forEach(b=>b.hidden=b.dataset.area!==area);$('moduleTitle').textContent={operation:'店铺运营',admin:'超级管理',brand:'品牌管理'}[area];current=key;tab='';page=1;query='';group='';status='';selected.clear();hiddenColumns.clear();const cfg=configs[key];$('detect').hidden=$('login').hidden=!isStore();document.querySelectorAll('[data-page]').forEach(b=>{b.classList.toggle('active',b.dataset.page===key);b.setAttribute('aria-current',b.dataset.page===key?'page':'false')});$('crumb').textContent=$('pageTitle').textContent=cfg.title;$('eyebrow').textContent=cfg.en;$('pageDescription').textContent=cfg.desc;$('add').textContent=cfg.add;$('batch').textContent=cfg.batch;$('keyword').value='';$('keyword').placeholder=cfg.search;$('groupFilter').innerHTML='<option value="">全部分组</option>'+cfg.groups.map(g=>`<option>${g}</option>`).join('');$('statusFilter').innerHTML='<option value="">全部状态</option>'+(isStore()?['正常','即将到期','已过期']:['正常','已停用']).map(s=>`<option>${s}</option>`).join('');render()}
function field(label,name,value='',required=false,type='text'){return `<div class="field"><label for="edit_${name}">${label}${required?' <span style="color:var(--brand)">*</span>':''}</label><input id="edit_${name}" name="${name}" type="${type}" value="${escapeHtml(value)}" maxlength="100" ${required?'required':''}></div>`}
function openEditor(id=null){editingId=id;const r=data[current].find(r=>r.id===id)||{},cfg=configs[current];$('editorTitle').textContent=id?'编辑'+(isStore()?'店铺':current==='oem'?'贴牌':'用户'):cfg.add;let fields=field(isStore()?'店铺名称':current==='oem'?'贴牌名称':'用户昵称','name',r.name,true)+field(isStore()?'店铺 ID':current==='oem'?'贴牌编码':'登录账号','code',r.code,true);if(current==='accounts'||current==='users')fields+=field('手机号','phone',r.phone,true)+field(id?'新密码(留空则不修改)':'密码','password','',!id,'password');fields+=`<div class="field"><label for="edit_group">所属分组</label><select name="group" id="edit_group">${cfg.groups.map(g=>`<option ${r.group===g?'selected':''}>${g}</option>`).join('')}</select></div>`;if(isStore()||current==='oem')fields+=field(current==='oem'?'主体账号':'子账号','account',r.account,current==='oem');if(current==='users')fields+=field('公司','company',r.company);if(!isStore())fields+=`<div class="field"><label for="edit_status">账号状态</label><select name="status" id="edit_status"><option ${r.status!=='已停用'?'selected':''}>正常</option><option ${r.status==='已停用'?'selected':''}>已停用</option></select></div>`;if(current==='accounts'||current==='users')fields+=`<div class="field"><label>可访问页面</label><div class="permissions">${['店铺列表','订单管理','商品采集','在线寄件','评分考核','税务申报'].map(p=>`<label><input type="checkbox" name="permission" value="${p}" ${(r.permissions||[]).includes(p)?'checked':''}>${p}</label>`).join('')}</div></div>`;fields+=field('备注','note',r.note);if(isStore()&&!id)fields+='<div class="help">此处演示手动添加流程。正式系统可在此接入扫码授权;新记录默认使用演示授权。</div>';$('editorFields').innerHTML=fields;$('editor').showModal()}
document.querySelectorAll('[data-page]').forEach(b=>b.onclick=()=>switchPage(b.dataset.page));
document.querySelectorAll('[data-module]').forEach(b=>b.onclick=()=>switchPage(b.dataset.start));
$('filterForm').onsubmit=e=>{e.preventDefault();query=$('keyword').value.trim().toLowerCase();group=$('groupFilter').value;status=$('statusFilter').value;page=1;selected.clear();renderTable()};
$('reset').onclick=()=>{query=group=status=tab='';page=1;selected.clear();$('keyword').value=$('groupFilter').value=$('statusFilter').value='';render()};
$('tabs').onclick=e=>{const b=e.target.closest('[data-tab]');if(b){tab=b.dataset.tab;page=1;selected.clear();renderTabs();renderTable()}};
$('prev').onclick=()=>{page--;renderTable()};$('next').onclick=()=>{page++;renderTable()};$('pageSize').onchange=()=>{page=1;renderTable()};
$('table').onchange=e=>{if(e.target.id==='selectAll')visibleRows().forEach(r=>e.target.checked?selected.add(r.id):selected.delete(r.id));else if(e.target.dataset.select){const id=Number(e.target.dataset.select);e.target.checked?selected.add(id):selected.delete(id)}renderTable()};
$('table').onclick=e=>{const action=e.target.closest('[data-store-action]');if(action){const r=data[current].find(r=>r.id===Number(action.dataset.id));if(action.dataset.storeAction==='renew'){r.status='正常';r.expires='2027-05-09';render();showToast('已模拟续期:'+r.name)}else{showToast('模拟进入店铺:'+r.name+'(未连接真实店铺)')}return}const edit=e.target.closest('[data-edit]'),detail=e.target.closest('[data-detail]');if(edit)openEditor(Number(edit.dataset.edit));if(detail){const r=data[current].find(r=>r.id===Number(detail.dataset.detail));$('detailTitle').textContent=r.name;$('detailBody').innerHTML=configs[current].columns.map(([key,label])=>`<div><div class="muted" style="font-size:11px;margin-bottom:6px">${label}</div>${cell(r,key)}</div>`).join('')+'<div class="notice">此为本地演示记录,不会连接店铺或读取真实账号。</div>';$('details').showModal()}if(e.target.id==='sortName'){sortAsc=!sortAsc;renderTable()}};
$('density').onclick=()=>{const compact=$('table').classList.toggle('compact');$('density').textContent=compact?'舒适视图':'紧凑视图';$('density').setAttribute('aria-pressed',compact)};
$('columnSettings').onclick=()=>{$('columnOptions').innerHTML=configs[current].columns.map(([key,label])=>`<label><input type="checkbox" value="${key}" ${hiddenColumns.has(key)?'':'checked'} ${key==='name'?'disabled':''}>${label}${key==='name'?'(固定)':''}</label>`).join('');$('columns').showModal()};
$('columnOptions').onchange=e=>{e.target.checked?hiddenColumns.delete(e.target.value):hiddenColumns.add(e.target.value);renderTable()};
$('add').onclick=()=>openEditor();document.querySelectorAll('[data-close]').forEach(b=>b.onclick=()=>$(b.dataset.close).close());
$('editForm').onsubmit=e=>{e.preventDefault();const values=new FormData(e.target),name=String(values.get('name')).trim(),code=String(values.get('code')).trim();if(!name||!code){showToast('名称和编号不能为空');return}if(data[current].some(r=>r.code===code&&r.id!==editingId)){showToast('该编号已存在,请使用其他编号');return}const existing=data[current].find(r=>r.id===editingId);const record={...(existing||{id:Date.now(),status:'正常',expires:'2027-05-09',owner:'demo_owner_1',points:0,balance:'0.00',fee:'2.50'}),name,code,group:values.get('group'),note:values.get('note'),permissions:values.getAll('permission')};for(const key of ['phone','account','company','status'])if(values.has(key))record[key]=values.get(key);if(existing)Object.assign(existing,record);else data[current].unshift(record);$('editor').close();render();showToast(editingId?'已保存修改(演示)':'已添加记录(演示)')};
$('batch').onclick=()=>{let count=selected.size;data[current].filter(r=>selected.has(r.id)).forEach(r=>{if(current!=='superstores'){r.status='正常';if(current==='stores')r.expires='2027-05-09'}});selected.clear();render();showToast(current==='superstores'?`已完成 ${count} 家店铺的模拟检测`:`已更新 ${count} 条演示记录`)};
$('detect').onclick=()=>{showToast('已模拟检测 '+selected.size+' 家店铺;登录状态已显示在表格中')};
$('login').onclick=()=>{data[current].filter(r=>selected.has(r.id)).forEach(r=>r.login='登录成功');renderTable();showToast('已模拟登录 '+selected.size+' 家店铺')};
$('refresh').onclick=()=>{render();$('loadStatus').textContent='已刷新 · '+new Date().toLocaleTimeString('zh-CN')+' · 本地演示';showToast('列表已刷新')};
$('designNotes').onclick=()=>{$('detailTitle').textContent='为桌面工作流而设计';$('detailBody').innerHTML='<div class="notice">品牌主色 #98638f · 梅紫</div><p>顶部以统一线性图标区分店铺运营、超级管理与品牌管理;左侧仅展示当前业务域内的功能。</p><p>工具栏按记录、选中记录、视图分组。新增和刷新位于左侧,批量操作居中,列设置与行密度位于右侧。筛选和状态切换贴近表格,选择数量在列表右上角显示。</p><p>默认紧凑行高 29px,舒适行高 36px;默认每页 50 条。表头与操作列固定,适合长列表与横向浏览。</p><p>后续 WPF 可使用 DockPanel / Grid 组织顶部模块栏、内容区与底部状态栏,业务页面复用 DataGridEx。此 HTML 仅演示交互,不包含权限校验、真实登录、支付续期或 API 接入。</p>';$('details').showModal()};
switchPage('stores');
console.assert(escapeHtml('<script>')==='&lt;script&gt;','HTML escaping');
console.assert(filtered().length===72,'Initial store count');
query='不存在的店铺';console.assert(filtered().length===0,'Empty search');query='';
status='已过期';console.assert(filtered().every(r=>r.status==='已过期'),'Status filter');status='';
console.assert(new Set(stores.map(r=>r.id)).size===stores.length,'Unique record IDs');
</script>
</body>
</html>
@@ -0,0 +1,8 @@
using System.Windows.Markup;
[assembly: XmlnsDefinition("MAX.Framework", "MAX.Framework")]
[assembly: XmlnsDefinition("MAX.Framework", "MAX.Framework.Extensions")]
[assembly: XmlnsDefinition("MAX.Framework", "MAX.Framework.Controls")]
[assembly: XmlnsDefinition("MAX.Framework", "MAX.Framework.Controls.Attach")]
[assembly: XmlnsPrefix("MAX.Framework", "mf")]
@@ -1,290 +0,0 @@
using MAX.Core.Commons;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace MAX.Framework.Controls;
public static class IDialogServiceExtension
{
public static void ShowDialog<TParameter>(this IDialogService dialogService, string name, TParameter parameter, Action<IDialogResult> callback) where TParameter : class
{
dialogService.ShowDialog(name, new DialogParameters
{
{"parameter", parameter},
}, callback);
}
public static void Show<TParameter>(this IDialogService dialogService, string name, TParameter parameter, Action<IDialogResult> callback) where TParameter : class
{
dialogService.Show(name, new DialogParameters
{
{"parameter", parameter},
}, callback);
}
}
/// <summary>
/// 确定取消对话框 ViewModel
/// </summary>
public class ConfirmDialogViewModel : BindableBase, IDialogAware
{
public ConfirmDialogViewModel()
{
}
private string title = "";
private bool _enableConfirm = true;
private bool _ShowConfirm = true;
private bool _ShowCancel = true;
private bool _ShowErrorMsg = true;
private string _ErrorMsg = "";
private string confirmText = "确定";
private string cancelText = "取消";
private string backText = "返回";
private bool allowEscape = true;
private bool allowEnter = true;
private bool isLoading = false;
public string Title
{
get => title;
protected set => SetProperty(ref title, value);
}
public bool AllowEscape
{
get => allowEscape;
set => SetProperty(ref allowEscape, value);
}
public bool AllowEnter
{
get => allowEnter;
set => SetProperty(ref allowEnter, value);
}
public bool IsLoading
{
get => isLoading;
set => SetProperty(ref isLoading, value, () =>
{
AllowEscape = !value;
AllowEnter = !value;
EnableConfirm = !value;
});
}
//<UserControl.Resources>
// <SolidColorBrush x:Key="RegionBrush" Color="Red"/>
// </UserControl.Resources>
private SolidColorBrush _Underpaint = new SolidColorBrush(Color.FromRgb(238, 238, 238));
/// <summary>
/// 背景底色
/// </summary>
public SolidColorBrush Underpaint
{
get => _Underpaint;
set => SetProperty(ref _Underpaint, value);
}
public event Action<IDialogResult> RequestClose;
protected void OnRequestClose(IDialogResult result)
{
RequestClose?.Invoke(result);
}
public virtual bool CanCloseDialog()
{
return true;
}
public virtual void OnDialogClosed()
{
}
public virtual void OnDialogOpened(IDialogParameters parameters)
{
}
public bool EnableConfirm
{
get => _enableConfirm;
set => SetProperty(ref _enableConfirm, value);
}
public bool ShowConfirm
{
get => _ShowConfirm;
set => SetProperty(ref _ShowConfirm, value);
}
public bool ShowCancel
{
get => _ShowCancel;
set => SetProperty(ref _ShowCancel, value);
}
public bool ShowErrorMsg
{
get => _ShowErrorMsg;
set => SetProperty(ref _ShowErrorMsg, value);
}
public string ConfirmText
{
get => confirmText;
set => SetProperty(ref confirmText, value);
}
public string CancelText
{
get => cancelText;
set => SetProperty(ref cancelText, value);
}
public string BackText
{
get => backText;
set => SetProperty(ref backText, value);
}
/// <summary>
/// 错误提示
/// </summary>
public string ErrorMsg
{
get => _ErrorMsg;
set => SetProperty(ref _ErrorMsg, value);
}
public virtual ICommand ConfirmCommand => new DelegateCommand(_Confirm);
protected virtual void _Confirm()
{
DialogResult ret = Confirm();
if (ret != null)
{
RequestClose?.Invoke(ret);
}
}
protected virtual DialogResult Confirm()
{
return new DialogResult(ButtonResult.OK);
}
public virtual ICommand CancelCommand => new DelegateCommand(_Cancel);
protected virtual void _Cancel()
{
DialogResult ret = Cancel();
if (ret != null)
{
RequestClose?.Invoke(ret);
}
else
{
RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
}
}
protected virtual DialogResult Cancel()
{
return new DialogResult(ButtonResult.Cancel);
}
public virtual void Loaded(object content)
{
var bb = Application.Current.TryFindResource("BackgroundBrush") as SolidColorBrush;
if (bb != null)
{
Underpaint = bb;
}
}
public class AsyncConfirmDialogViewModel : ConfirmDialogViewModel
{
public override ICommand ConfirmCommand => new AsyncDelegateCommand(_Confirm);
protected new async Task _Confirm()
{
DialogResult ret = await Confirm();
if (ret != null)
{
OnRequestClose(ret);
}
}
protected new virtual async Task<DialogResult> Confirm()
{
return await Task.FromResult(new DialogResult(ButtonResult.OK));
}
}
public interface IDialogClassParameters
{
}
}
/// 确定取消对话框
/// </summary>
/// <typeparam name="TParameter">参数Model</typeparam>
public class ConfirmDialogViewModel<TParameter> : ConfirmDialogViewModel where TParameter : class
{
protected TParameter Args { get; set; }
public override void OnDialogOpened(IDialogParameters parameters)
{
base.OnDialogOpened(parameters);
if (parameters.TryGetValue("parameter", out TParameter parameter))
{
Args = parameter;
}
}
}
public abstract class ConfirmDialogViewModel<TParameter, TResult> : ConfirmDialogViewModel where TParameter : class where TResult : DialogResult/*, new()*/
{
protected TParameter Args { get; set; }
public override void OnDialogOpened(IDialogParameters parameters)
{
base.OnDialogOpened(parameters);
if (parameters.TryGetValue("parameter", out TParameter parameter))
{
Args = parameter;
}
}
protected override void _Confirm()
{
TResult ret = Confirm();
if (ret != null)
{
base.OnRequestClose(ret);
}
}
protected new abstract TResult Confirm();
protected override void _Cancel()
{
TResult ret = Cancel();
if (ret != null)
{
base.OnRequestClose(ret);
}
else
{
base.OnRequestClose(new DialogResult(ButtonResult.Cancel));
}
}
protected new abstract TResult Cancel();
}
//public abstract class ConfirmDialogParameterViewModel : ConfirmDialogViewModel<ConfirmDialogParameterViewModel.Parameter>
//{
// public abstract class Parameter;
//}
@@ -16,4 +16,8 @@
<ProjectReference Include="..\MAX.Core\MAX.Core.csproj" /> <ProjectReference Include="..\MAX.Core\MAX.Core.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Controls\Attach\" />
</ItemGroup>
</Project> </Project>
@@ -3,7 +3,6 @@ namespace Store.Management.Api;
public sealed class ApiClientOptions public sealed class ApiClientOptions
{ {
public required Uri BaseUrl { get; init; } public required Uri BaseUrl { get; init; }
public string Version { get; init; } = "v1";
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30); public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
internal void Validate() internal void Validate()
@@ -12,8 +11,6 @@ public sealed class ApiClientOptions
(BaseUrl.Scheme != "https" && BaseUrl.Scheme != "http") || (BaseUrl.Scheme != "https" && BaseUrl.Scheme != "http") ||
!string.IsNullOrEmpty(BaseUrl.UserInfo) || !string.IsNullOrEmpty(BaseUrl.Query) || !string.IsNullOrEmpty(BaseUrl.Fragment)) !string.IsNullOrEmpty(BaseUrl.UserInfo) || !string.IsNullOrEmpty(BaseUrl.Query) || !string.IsNullOrEmpty(BaseUrl.Fragment))
throw new ArgumentException("BaseUrl 必须是无凭据、查询参数和片段的 HTTP(S) 绝对地址。"); throw new ArgumentException("BaseUrl 必须是无凭据、查询参数和片段的 HTTP(S) 绝对地址。");
if (!System.Text.RegularExpressions.Regex.IsMatch(Version, @"^v\d+(\.\d+)?$"))
throw new ArgumentException("Version 格式应为 v1 或 v1.0。");
if (Timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Timeout)); if (Timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Timeout));
} }
} }
@@ -1,3 +1,4 @@
using Store.Management.Models;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using RestSharp; using RestSharp;
using Store.Management.Api.Transport; using Store.Management.Api.Transport;
@@ -13,23 +14,7 @@ public sealed class LoginRequest
[StringLength(100)] public string? DeviceName { get; set; } [StringLength(100)] public string? DeviceName { get; set; }
} }
public sealed class LoginResult public sealed class AuthApi(ApiTransport transport, TokenSession session)
{
public string TokenType { get; init; } = "Bearer";
public string Token { get; init; } = "";
public uint ExpiresInMinutes { get; init; }
}
public sealed record CurrentUser(string UserName, string? NickName);
public interface IAuthApi
{
Task<LoginResult> LoginAsync(LoginRequest request, CancellationToken cancellationToken = default);
Task LogoutAsync(CancellationToken cancellationToken = default);
Task<CurrentUser> MeAsync(CancellationToken cancellationToken = default);
}
internal sealed class AuthApi(ApiTransport transport, TokenSession session) : IAuthApi
{ {
// 登录和退出串行执行,避免迟到的登录响应覆盖退出操作。 // 登录和退出串行执行,避免迟到的登录响应覆盖退出操作。
private readonly SemaphoreSlim _gate = new(1, 1); private readonly SemaphoreSlim _gate = new(1, 1);
@@ -7,7 +7,6 @@ public sealed class ApiResult<T>
public string? TraceId { get; init; } public string? TraceId { get; init; }
public T? Data { get; init; } public T? Data { get; init; }
} }
public sealed record PageResult<T>(long Total, IReadOnlyList<T> Items); public sealed record PageResult<T>(long Total, IReadOnlyList<T> Items);
public class PageRequest public class PageRequest
@@ -0,0 +1,25 @@
using RestSharp;
using Store.Management.Api.Models;
using Store.Management.Api.Transport;
using Store.Management.Models;
namespace Store.Management.Api.Shops;
public sealed class ShopApi(ApiTransport transport)
{
/// <summary>按店铺 ID 获取 Cookie,仅在用户请求时读取。</summary>
public Task<IReadOnlyList<ShopCookieInfo>> GetCookiesAsync(string shopId, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(shopId);
return transport.GetRequiredAsync<IReadOnlyList<ShopCookieInfo>>("shop/GetShopCookies", Method.Post,
new { ShopIds = new[] { shopId } }, cancellationToken: cancellationToken);
}
/// <summary>管理员分页查询商铺,筛选条件由服务端处理。</summary>
public Task<PageResult<ShopInfo>> SearchAsync(ShopQueryRequest request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
return transport.GetRequiredAsync<PageResult<ShopInfo>>("shop/GetAllShops", Method.Post,
request, cancellationToken: cancellationToken);
}
}
@@ -0,0 +1,11 @@
using Store.Management.Api.Models;
namespace Store.Management.Api.Shops;
public sealed class ShopQueryRequest : PageRequest
{
public string? SearchUserName { get; init; }
public string? SearchId { get; init; }
public string? SearchName { get; init; }
public string? SearchNotes { get; init; }
}
@@ -4,4 +4,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="RestSharp" Version="112.1.0" /> <PackageReference Include="RestSharp" Version="112.1.0" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Store.Management.Models\Store.Management.Models.csproj" />
</ItemGroup>
</Project> </Project>
+22 -17
View File
@@ -7,23 +7,28 @@ namespace Store.Management.Api;
/// <summary>一个服务地址与一个用户会话对应一个实例;在应用容器中注册为单例。</summary> /// <summary>一个服务地址与一个用户会话对应一个实例;在应用容器中注册为单例。</summary>
public sealed class StoreApiClient : IDisposable public sealed class StoreApiClient : IDisposable
{ {
public TokenSession Session { get; } = new(); public TokenSession Session { get; } = new();
public ApiTransport Transport { get; } public ApiTransport Transport { get; }
public IAuthApi Auth { get; } public AuthApi Auth { get; }
public IUserApi Users { get; } public UserApi Users { get; }
public Shops.ShopApi Shops { get; }
/// <param name="httpClient">可选的外部 HTTP 客户端,由调用方管理其生命周期。</param> /// <param name="httpClient">可选的外部 HTTP 客户端,由调用方管理其生命周期。</param>
public StoreApiClient(ApiClientOptions options, HttpClient? httpClient = null) public StoreApiClient(ApiClientOptions options, HttpClient? httpClient = null)
{ {
ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(options);
Transport = new ApiTransport(options, Session, httpClient); #if DEBUG
Auth = new AuthApi(Transport, Session); Session.Set("store-local-dev-7f2c9e4a6b814d38a5910e62c4f837bd");
Users = new UserApi(Transport); #endif
} Transport = new ApiTransport(options, Session, httpClient);
Auth = new AuthApi(Transport, Session);
Users = new UserApi(Transport);
Shops = new Shops.ShopApi(Transport);
}
public void Dispose() public void Dispose()
{ {
Session.Clear(); Session.Clear();
Transport.Dispose(); Transport.Dispose();
} }
} }
@@ -12,14 +12,12 @@ public sealed class ApiTransport : IDisposable
{ {
private readonly RestClient _client; private readonly RestClient _client;
private readonly TokenSession _session; private readonly TokenSession _session;
private readonly string _version;
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
internal ApiTransport(ApiClientOptions options, TokenSession session, HttpClient? httpClient) internal ApiTransport(ApiClientOptions options, TokenSession session, HttpClient? httpClient)
{ {
options.Validate(); options.Validate();
_session = session; _session = session;
_version = options.Version;
RestClientOptions settings = new RestClientOptions(new Uri(options.BaseUrl.AbsoluteUri.TrimEnd('/') + "/")) RestClientOptions settings = new RestClientOptions(new Uri(options.BaseUrl.AbsoluteUri.TrimEnd('/') + "/"))
{ {
Timeout = options.Timeout, Timeout = options.Timeout,
@@ -47,7 +45,7 @@ public sealed class ApiTransport : IDisposable
{ {
throw new ApiException(ApiErrorKind.Unauthorized, "请先登录。", code: 401); throw new ApiException(ApiErrorKind.Unauthorized, "请先登录。", code: 401);
} }
RestRequest request = new RestRequest($"{_version}/{route}", method); RestRequest request = new RestRequest($"/{route}", method);
if (token is not null) if (token is not null)
{ {
request.AddHeader("Authorization", $"Bearer {token}"); request.AddHeader("Authorization", $"Bearer {token}");
+18 -9
View File
@@ -1,18 +1,12 @@
using RestSharp; using RestSharp;
using Store.Management.Api.Models; using Store.Management.Api.Models;
using Store.Management.Api.Transport; using Store.Management.Api.Transport;
using Store.Management.Models;
namespace Store.Management.Api.Users; namespace Store.Management.Api.Users;
public interface IUserApi
{
Task<PageResult<UserInfo>> SearchAsync(UserSearchRequest request, CancellationToken cancellationToken = default);
Task<UserInfo> GetAsync(string? userName = null, CancellationToken cancellationToken = default);
Task<UserInfo> CreateAsync(UserCreateRequest request, CancellationToken cancellationToken = default);
Task<UserInfo> UpdateAsync(UserUpdateRequest request, CancellationToken cancellationToken = default);
}
internal sealed class UserApi(ApiTransport transport) : IUserApi public sealed class UserApi(ApiTransport transport)
{ {
public Task<PageResult<UserInfo>> SearchAsync(UserSearchRequest request, CancellationToken cancellationToken = default) public Task<PageResult<UserInfo>> SearchAsync(UserSearchRequest request, CancellationToken cancellationToken = default)
{ {
@@ -27,9 +21,24 @@ internal sealed class UserApi(ApiTransport transport) : IUserApi
public Task<UserInfo> CreateAsync(UserCreateRequest request, CancellationToken cancellationToken = default) public Task<UserInfo> CreateAsync(UserCreateRequest request, CancellationToken cancellationToken = default)
{ {
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request);
return transport.GetRequiredAsync<UserInfo>("user/AddUser", Method.Post, request, cancellationToken: cancellationToken); string route = request.GroupId is null or UserGroup.MainAccount ? "user/AddUser" : "user/AddSubUser";
return transport.GetRequiredAsync<UserInfo>(route, Method.Post, request, cancellationToken: cancellationToken);
} }
public Task ChangePasswordAsync(ChangePasswordRequest request, CancellationToken cancellationToken = default)
=> transport.SendAsync<object>("user/ChangePassword", Method.Post, request, cancellationToken: cancellationToken);
public Task DeleteAsync(int id, CancellationToken cancellationToken = default)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(id);
return transport.SendAsync<object>("user/DelUser", Method.Post,
query: new Dictionary<string, string?> { ["id"] = id.ToString(System.Globalization.CultureInfo.InvariantCulture) },
cancellationToken: cancellationToken);
}
public Task<UserInfo> UpdateBillingAsync(UserBillingUpdateRequest request, CancellationToken cancellationToken = default)
=> transport.GetRequiredAsync<UserInfo>("user/UpdateUser", Method.Post, request, cancellationToken: cancellationToken);
public Task<UserInfo> UpdateAsync(UserUpdateRequest request, CancellationToken cancellationToken = default) public Task<UserInfo> UpdateAsync(UserUpdateRequest request, CancellationToken cancellationToken = default)
{ {
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request);
+21 -13
View File
@@ -1,4 +1,6 @@
using Store.Management.Models;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using Store.Management.Api.Models; using Store.Management.Api.Models;
namespace Store.Management.Api.Users; namespace Store.Management.Api.Users;
@@ -6,12 +8,16 @@ namespace Store.Management.Api.Users;
public sealed class UserSearchRequest : PageRequest public sealed class UserSearchRequest : PageRequest
{ {
[StringLength(100)] public string? Keyword { get; set; } [StringLength(100)] public string? Keyword { get; set; }
public int? GroupId { get; set; } public int? GroupId { get; set; }
[StringLength(20)] public string? ParentUserName { get; set; } [StringLength(20)] public string? ParentUserName { get; set; }
} }
public class UserEditRequest public class UserEditRequest
{ {
public UserGroup? GroupId { get; set; }
public UserAdminLevel? SaLevel { get; set; }
[StringLength(50)] public string? OemId { get; set; }
[StringLength(1000)] public string? Authority { get; set; }
[StringLength(50)] public string? NickName { get; set; } [StringLength(50)] public string? NickName { get; set; }
[StringLength(30)] public string? Mobile { get; set; } [StringLength(30)] public string? Mobile { get; set; }
[StringLength(100)] public string? CompanyName { get; set; } [StringLength(100)] public string? CompanyName { get; set; }
@@ -25,22 +31,24 @@ public sealed class UserCreateRequest : UserEditRequest
[StringLength(20)] public string? ParentUserName { get; set; } [StringLength(20)] public string? ParentUserName { get; set; }
} }
public sealed record ChangePasswordRequest(string UserName, string NewPassword, string? OldPassword = null);
public sealed class UserUpdateRequest : UserEditRequest public sealed class UserUpdateRequest : UserEditRequest
{ {
[Range(1, int.MaxValue)] public int Id { get; set; } [Range(1, int.MaxValue)] public int Id { get; set; }
} }
/// <summary>管理端当前使用的用户资料字段;不接收密码。</summary> public sealed class UserBillingUpdateRequest
public sealed class UserInfo
{ {
public int Id { get; init; } [Range(1, int.MaxValue)] public int Id { get; init; }
public string UserName { get; init; } = ""; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? NickName { get; init; } public int? ShopPointsPerMonth { get; set; }
public string? Mobile { get; init; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? CompanyName { get; init; } public decimal? PostagePerOrder { get; set; }
public string? Notes { get; init; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? ParentUserName { get; init; } public decimal? RefundPostagePerOrder { get; set; }
public int GroupId { get; init; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public decimal Points { get; init; } public decimal? GiftOemAmountPerOrder { get; set; }
public decimal? Balance { get; init; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public decimal? SyncLogisticsPerOrder { get; set; }
} }
@@ -24,7 +24,7 @@ public sealed class FolderConfig : IFolderConfig
/// <summary>当前用户的数据根目录:%LOCALAPPDATA%\Store.Management。</summary> /// <summary>当前用户的数据根目录:%LOCALAPPDATA%\Store.Management。</summary>
public static string AppFolder => Path.Combine( public static string AppFolder => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppName); Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppName);
//, MAX.Core.Cryptography.MD5Helper.Md5_32(ExeFolder)
public static string ConfigFolder => Path.Combine(AppFolder, "Config"); public static string ConfigFolder => Path.Combine(AppFolder, "Config");
public static string DataFolder => Path.Combine(AppFolder, "Data"); public static string DataFolder => Path.Combine(AppFolder, "Data");
public static string LoggingFolder => Path.Combine(AppFolder, "Logs"); public static string LoggingFolder => Path.Combine(AppFolder, "Logs");
@@ -5,7 +5,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
namespace MAX.Framework.Controls.Attach; namespace Store.Management.Framework.Controls.Attach;
/// <summary> /// <summary>
/// 弹出窗口属性值 /// 弹出窗口属性值
@@ -32,7 +32,7 @@ public static class IDialogServiceExtension
/// <summary> /// <summary>
/// 确定取消对话框 ViewModel /// 确定取消对话框 ViewModel
/// </summary> /// </summary>
public class ConfirmDialogViewModel : BindableBase, IDialogAware public class ConfirmDialogViewModel : ViewModelBase, IDialogAware
{ {
public ConfirmDialogViewModel() public ConfirmDialogViewModel()
{ {
@@ -124,7 +124,7 @@ public partial class DataGridEx : DataGrid
public bool? AreAllRowsSelected => (bool?)GetValue(AreAllRowsSelectedProperty); public bool? AreAllRowsSelected => (bool?)GetValue(AreAllRowsSelectedProperty);
public static readonly DependencyProperty SelectedRowBackgroundProperty = DependencyProperty.Register( public static readonly DependencyProperty SelectedRowBackgroundProperty = DependencyProperty.Register(
nameof(SelectedRowBackground), typeof(Brush), typeof(DataGridEx), nameof(SelectedRowBackground), typeof(Brush), typeof(DataGridEx),
new PropertyMetadata((Brush)new BrushConverter().ConvertFromString("#F3EAF1")!)); new PropertyMetadata(Brushes.LightGray));
public static readonly DependencyProperty SelectedRowForegroundProperty = DependencyProperty.Register( public static readonly DependencyProperty SelectedRowForegroundProperty = DependencyProperty.Register(
nameof(SelectedRowForeground), typeof(Brush), typeof(DataGridEx), new PropertyMetadata(Brushes.Black)); nameof(SelectedRowForeground), typeof(Brush), typeof(DataGridEx), new PropertyMetadata(Brushes.Black));
public static readonly DependencyProperty ShowCheckBoxProperty = DependencyProperty.Register( public static readonly DependencyProperty ShowCheckBoxProperty = DependencyProperty.Register(
@@ -1,17 +1,22 @@
<ResourceDictionary <ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Store.Management.Framework.Controls" xmlns:ext="clr-namespace:Store.Management.Framework.Controls"
xmlns:ext="clr-namespace:Store.Management.Framework.Controls" xmlns:f="clr-namespace:Store.Management.Framework.Controls.Attach;assembly=Store.Management.Framework"
xmlns:f="clr-namespace:Store.Management.Framework.Controls.Attach;assembly=Store.Management.Framework" xmlns:local="clr-namespace:Store.Management.Framework.Controls"
xmlns:sys="clr-namespace:System;assembly=mscorlib"> xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:wpf="MAX.WPF">
<sys:Double x:Key="DataGridExFontSize">12</sys:Double> <sys:Double x:Key="DataGridExFontSize">12</sys:Double>
<FontFamily x:Key="DataGridExFontFamily">Microsoft YaHei UI, Segoe UI</FontFamily> <FontFamily x:Key="DataGridExFontFamily">Microsoft YaHei UI, Segoe UI</FontFamily>
<BooleanToVisibilityConverter x:Key="DataGridExVisibility"/> <wpf:ThicknessSplitConverter x:Key="DataGridExBorderThicknessSplit" />
<Style x:Key="DataGridExCheckBoxStyle" TargetType="CheckBox" BasedOn="{StaticResource {x:Type CheckBox}}"/> <BooleanToVisibilityConverter x:Key="DataGridExVisibility" />
<Style x:Key="DataGridExDefaultCellHeaderStyle" TargetType="DataGridColumnHeader"> <Style
x:Key="DataGridExCheckBoxStyle"
BasedOn="{StaticResource {x:Type CheckBox}}"
TargetType="CheckBox" />
<Style x:Key="DataGridExDefaultCellHeaderStyle" TargetType="DataGridColumnHeader">
<Setter Property="UseLayoutRounding" Value="True" /> <Setter Property="UseLayoutRounding" Value="True" />
<!--<Setter Property="f:DataGridHelper.ShowBorder" Value="True" />--> <!--<Setter Property="f:DataGridHelper.ShowBorder" Value="True" />-->
@@ -171,7 +176,7 @@
</Grid> </Grid>
<ControlTemplate.Triggers> <ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True"> <Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="White" /> <Setter Property="Foreground" Value="{Binding SelectedRowForeground, RelativeSource={RelativeSource AncestorType={x:Type local:DataGridEx}}}" />
</Trigger> </Trigger>
</ControlTemplate.Triggers> </ControlTemplate.Triggers>
</ControlTemplate> </ControlTemplate>
@@ -198,7 +203,7 @@
</Border> </Border>
<ControlTemplate.Triggers> <ControlTemplate.Triggers>
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}}" Value="True"> <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}}" Value="True">
<Setter Property="Foreground" Value="White" /> <Setter Property="Foreground" Value="{Binding SelectedRowForeground, RelativeSource={RelativeSource AncestorType={x:Type local:DataGridEx}}}" />
</DataTrigger> </DataTrigger>
</ControlTemplate.Triggers> </ControlTemplate.Triggers>
</ControlTemplate> </ControlTemplate>
@@ -240,7 +245,8 @@
Grid.Column="1" Grid.Column="1"
SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical}, Converter={x:Static DataGrid.RowDetailsScrollingConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical}, Converter={x:Static DataGrid.RowDetailsScrollingConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
Visibility="{TemplateBinding DetailsVisibility}" /> Visibility="{TemplateBinding DetailsVisibility}" />
<DataGridRowHeader x:Name="PART_RowHeader" <DataGridRowHeader
x:Name="PART_RowHeader"
Grid.RowSpan="2" Grid.RowSpan="2"
SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical" SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" /> Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
@@ -328,7 +334,7 @@
<Trigger Property="IsSelected" Value="True"> <Trigger Property="IsSelected" Value="True">
<Setter TargetName="fousIcon" Property="Opacity" Value="1" /> <Setter TargetName="fousIcon" Property="Opacity" Value="1" />
<!-- 整行变色 --> <!-- 整行变色 -->
<Setter TargetName="border" Property="Background" Value="#4BB2FF" /> <Setter TargetName="border" Property="Background" Value="{Binding SelectedRowBackground, RelativeSource={RelativeSource AncestorType={x:Type local:DataGridEx}}}" />
</Trigger> </Trigger>
<Trigger Property="DetailsVisibility" Value="Visible"> <Trigger Property="DetailsVisibility" Value="Visible">
<Setter TargetName="DetailsPresenter" Property="Margin" Value="0,0,1,0" /> <Setter TargetName="DetailsPresenter" Property="Margin" Value="0,0,1,0" />
@@ -355,84 +361,125 @@
</Style> </Style>
<Style x:Key="DataGridExDefaultDataGridStyle" TargetType="local:DataGridEx"> <Style x:Key="DataGridExDefaultDataGridStyle" TargetType="local:DataGridEx">
<Style.Resources> <Style.Resources>
<Style x:Key="DataGridExColumnMenu" TargetType="ContextMenu"> <Style x:Key="DataGridExColumnMenu" TargetType="ContextMenu">
<Setter Property="Width" Value="240"/> <Setter Property="Width" Value="240" />
<Setter Property="FontSize" Value="12"/> <Setter Property="FontSize" Value="12" />
<Setter Property="Foreground" Value="#343A40"/> <Setter Property="Foreground" Value="#343A40" />
<Setter Property="Template"> <Setter Property="Template">
<Setter.Value> <Setter.Value>
<ControlTemplate TargetType="ContextMenu"> <ControlTemplate TargetType="ContextMenu">
<Border Background="White" BorderBrush="#DDE0E5" BorderThickness="1" CornerRadius="6" Padding="0"> <Border
<StackPanel KeyboardNavigation.DirectionalNavigation="Cycle"> Background="White"
<StackPanel Margin="14,12,14,8"> BorderBrush="LightGray"
<TextBlock Text="显示的列" FontSize="14" FontWeight="SemiBold"/> BorderThickness="1">
<TextBlock Text="勾选后立即生效" Foreground="#858A94" Margin="0,4,0,0"/> <StackPanel KeyboardNavigation.DirectionalNavigation="Cycle">
</StackPanel>
<ScrollViewer MaxHeight="340" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Margin="6,0,6,8"> <Border
<ItemsPresenter KeyboardNavigation.DirectionalNavigation="Cycle"/> Padding="10,0"
</ScrollViewer> Background="#eeeeee"
<Border BorderBrush="#ECEEF1" BorderThickness="0,1,0,0" Padding="12,9" Background="#FAFAFB"> BorderBrush="{StaticResource BorderBrush}"
<Button x:Name="PART_DoneButton" Content="完成" HorizontalAlignment="Right" Width="64" Height="28" BorderThickness="0,0,0,1">
Command="{x:Static ApplicationCommands.Close}" <Grid>
Foreground="White" Background="#98638F" BorderThickness="0"> <TextBlock
<Button.Template> VerticalAlignment="Center"
<ControlTemplate TargetType="Button"> FontSize="14"
<Border x:Name="ButtonBorder" Background="{TemplateBinding Background}" CornerRadius="4"> FontWeight="SemiBold"
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> Text="显示的列" />
</Border> <Button
<ControlTemplate.Triggers> Width="64"
<Trigger Property="IsMouseOver" Value="True"><Setter TargetName="ButtonBorder" Property="Opacity" Value="0.85"/></Trigger> Height="28"
<Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="ButtonBorder" Property="BorderBrush" Value="#343A40"/><Setter TargetName="ButtonBorder" Property="BorderThickness" Value="1"/></Trigger> HorizontalAlignment="Right"
</ControlTemplate.Triggers> Background="Transparent"
</ControlTemplate> BorderThickness="0"
</Button.Template> Command="{x:Static ApplicationCommands.Close}"
</Button> Content="完成"
</Border> Style="{x:Null}" />
</StackPanel> </Grid>
</Border>
</ControlTemplate> </Border>
</Setter.Value>
</Setter> <ScrollViewer
<Setter Property="ItemContainerStyle"> MaxHeight="340"
<Setter.Value> HorizontalScrollBarVisibility="Disabled"
<Style TargetType="MenuItem"> VerticalScrollBarVisibility="Auto">
<Setter Property="Height" Value="30"/> <ItemsPresenter KeyboardNavigation.DirectionalNavigation="Cycle" />
<Setter Property="Padding" Value="8,0"/> </ScrollViewer>
<Setter Property="Template">
<Setter.Value> </StackPanel>
<ControlTemplate TargetType="MenuItem"> </Border>
<Border x:Name="ItemBorder" Background="Transparent" CornerRadius="4" Padding="{TemplateBinding Padding}"> </ControlTemplate>
<Grid> </Setter.Value>
<Grid.ColumnDefinitions><ColumnDefinition Width="24"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions> </Setter>
<Border x:Name="CheckBorder" Width="14" Height="14" HorizontalAlignment="Left" VerticalAlignment="Center" <Setter Property="ItemContainerStyle">
BorderBrush="#C8CDD4" BorderThickness="1" CornerRadius="3" Background="White"> <Setter.Value>
<Path x:Name="CheckMark" Data="M 2,6 L 5,9 L 11,3" Stroke="White" StrokeThickness="1.5" Visibility="Collapsed"/> <Style TargetType="MenuItem">
</Border> <Setter Property="Height" Value="30" />
<ContentPresenter Grid.Column="1" ContentSource="Header" VerticalAlignment="Center"/> <Setter Property="Padding" Value="8,0" />
</Grid> <Setter Property="Template">
</Border> <Setter.Value>
<ControlTemplate.Triggers> <ControlTemplate TargetType="MenuItem">
<Trigger Property="IsHighlighted" Value="True"><Setter TargetName="ItemBorder" Property="Background" Value="#F3F4F6"/></Trigger> <Border
<Trigger Property="IsChecked" Value="True"> x:Name="ItemBorder"
<Setter TargetName="CheckBorder" Property="Background" Value="#98638F"/> Padding="{TemplateBinding Padding}"
<Setter TargetName="CheckBorder" Property="BorderBrush" Value="#98638F"/> Background="Transparent"
<Setter TargetName="CheckMark" Property="Visibility" Value="Visible"/> CornerRadius="4">
</Trigger> <Grid>
<Trigger Property="IsEnabled" Value="False"> <Grid.ColumnDefinitions>
<Setter Property="Foreground" Value="#8A8F98"/> <ColumnDefinition Width="24" />
<Setter TargetName="CheckBorder" Property="Background" Value="#D5D8DE"/> <ColumnDefinition Width="*" />
<Setter TargetName="CheckBorder" Property="BorderBrush" Value="#D5D8DE"/> </Grid.ColumnDefinitions>
</Trigger> <Border
</ControlTemplate.Triggers> x:Name="CheckBorder"
</ControlTemplate> Width="14"
</Setter.Value> Height="14"
</Setter> HorizontalAlignment="Left"
</Style> VerticalAlignment="Center"
</Setter.Value> Background="White"
</Setter> BorderBrush="#C8CDD4"
</Style> BorderThickness="1"
</Style.Resources> CornerRadius="3">
<Path
x:Name="CheckMark"
Data="M 2,6 L 5,9 L 11,3"
Stroke="White"
StrokeThickness="1.5"
Visibility="Collapsed" />
</Border>
<ContentPresenter
Grid.Column="1"
VerticalAlignment="Center"
ContentSource="Header" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="ItemBorder" Property="Background" Value="#F3F4F6" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="CheckBorder" Property="Background" Value="#98638F" />
<Setter TargetName="CheckBorder" Property="BorderBrush" Value="#98638F" />
<Setter TargetName="CheckMark" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="#8A8F98" />
<Setter TargetName="CheckBorder" Property="Background" Value="#D5D8DE" />
<Setter TargetName="CheckBorder" Property="BorderBrush" Value="#D5D8DE" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
</Style.Resources>
<Setter Property="PageSizes">
<Setter.Value>
<Int32Collection>50,100,500,1000,2000</Int32Collection>
</Setter.Value>
</Setter>
<Setter Property="UseLayoutRounding" Value="True" /> <Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="SnapsToDevicePixels" Value="True" /> <Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Background" Value="White" /> <Setter Property="Background" Value="White" />
@@ -449,7 +496,7 @@
<Setter Property="VerticalContentAlignment" Value="Center" /> <Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Foreground" Value="#343A40" /> <Setter Property="Foreground" Value="#343A40" />
<Setter Property="BorderBrush" Value="#E1E4E8" /> <Setter Property="BorderBrush" Value="#E1E4E8" />
<Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderThickness" Value="1" />
<Setter Property="VerticalGridLinesBrush" Value="#E1E4E8" /> <Setter Property="VerticalGridLinesBrush" Value="#E1E4E8" />
<Setter Property="HorizontalGridLinesBrush" Value="#E1E4E8" /> <Setter Property="HorizontalGridLinesBrush" Value="#E1E4E8" />
<Setter Property="RowDetailsVisibilityMode" Value="VisibleWhenSelected" /> <Setter Property="RowDetailsVisibilityMode" Value="VisibleWhenSelected" />
@@ -466,194 +513,262 @@
<Setter.Value> <Setter.Value>
<ControlTemplate TargetType="{x:Type local:DataGridEx}"> <ControlTemplate TargetType="{x:Type local:DataGridEx}">
<Grid> <Grid>
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions> <Grid.RowDefinitions>
<!-- 调用方可以提供批量操作内容,默认展示选择提示和列设置。 --> <RowDefinition Height="Auto" />
<Border x:Name="PART_ToolbarArea" Grid.Row="0" Background="#FAFAFA" BorderBrush="#E1E4E8" BorderThickness="1,1,1,0" Padding="8,5" <RowDefinition Height="*" />
Visibility="{Binding ShowToolbar, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay, Converter={StaticResource DataGridExVisibility}}"> <RowDefinition Height="Auto" />
<DockPanel LastChildFill="True"> </Grid.RowDefinitions>
<Button x:Name="PART_ColumnsButton" DockPanel.Dock="Right" Content="列设置" Padding="10,3" MinHeight="26" <!-- 调用方可以提供批量操作内容,默认展示选择提示和列设置。 -->
Visibility="{Binding ShowColumnSettings, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay, Converter={StaticResource DataGridExVisibility}}"/> <Border
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="0,0,12,0" x:Name="PART_ToolbarArea"
Text="{Binding SelectionSummary, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}"/> Grid.Row="0"
<ContentPresenter Content="{TemplateBinding ToolbarContent}" VerticalAlignment="Center"/> Padding="8,5"
</DockPanel> Background="#FAFAFA"
</Border> BorderBrush="{TemplateBinding BorderBrush}"
<!-- 原生 DataGrid 滚动与虚拟化宿主。 --> BorderThickness="{Binding BorderThickness, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource DataGridExBorderThicknessSplit}, ConverterParameter='1,1,1,0'}"
<Border x:Name="PART_TableArea" Grid.Row="1" Visibility="{Binding ShowToolbar, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay, Converter={StaticResource DataGridExVisibility}}">
Padding="{TemplateBinding Padding}" <DockPanel LastChildFill="True">
Background="{TemplateBinding Background}" <Button
BorderBrush="{TemplateBinding BorderBrush}" x:Name="PART_ColumnsButton"
BorderThickness="{TemplateBinding BorderThickness}" MinHeight="26"
SnapsToDevicePixels="True" Padding="10,3"
UseLayoutRounding="True"> Content="列设置"
<ScrollViewer x:Name="DG_ScrollViewer" Focusable="false"> DockPanel.Dock="Right"
<ScrollViewer.Template> Visibility="{Binding ShowColumnSettings, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay, Converter={StaticResource DataGridExVisibility}}" />
<ControlTemplate TargetType="{x:Type ScrollViewer}"> <TextBlock
<Grid> Margin="0,0,12,0"
<Grid.ColumnDefinitions> VerticalAlignment="Center"
<ColumnDefinition Width="Auto" /> DockPanel.Dock="Left"
<ColumnDefinition Width="*" /> Text="{Binding SelectionSummary, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" />
<ColumnDefinition Width="Auto" /> <ContentPresenter VerticalAlignment="Center" Content="{TemplateBinding ToolbarContent}" />
</Grid.ColumnDefinitions> </DockPanel>
<Grid.RowDefinitions> </Border>
<RowDefinition Height="Auto" /> <!-- 原生 DataGrid 滚动与虚拟化宿主。 -->
<RowDefinition Height="*" /> <Border
<RowDefinition Height="Auto" /> x:Name="PART_TableArea"
</Grid.RowDefinitions> Grid.Row="1"
<Border Padding="{TemplateBinding Padding}"
Grid.Row="0" Background="{TemplateBinding Background}"
Grid.Column="0" BorderBrush="{TemplateBinding BorderBrush}"
Width="{Binding CellsPanelHorizontalOffset, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" BorderThickness="{TemplateBinding BorderThickness}"
Background="#eeeeee" SnapsToDevicePixels="True"
BorderBrush="{Binding BorderBrush, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" UseLayoutRounding="True">
BorderThickness="0,0,1,1"> <ScrollViewer x:Name="DG_ScrollViewer" Focusable="false">
<CheckBox <ScrollViewer.Template>
Width="16" <ControlTemplate TargetType="{x:Type ScrollViewer}">
HorizontalAlignment="Center" <Grid>
VerticalAlignment="Center" <Grid.ColumnDefinitions>
HorizontalContentAlignment="Center" <ColumnDefinition Width="Auto" />
AutomationProperties.Name="全选行" <ColumnDefinition Width="*" />
Command="{x:Static ext:DataGridEx.ToggleSelectAllCommand}" <ColumnDefinition Width="Auto" />
CommandTarget="{Binding RelativeSource={RelativeSource AncestorType={x:Type ext:DataGridEx}}}" </Grid.ColumnDefinitions>
IsChecked="{Binding AreAllRowsSelected, RelativeSource={RelativeSource AncestorType={x:Type ext:DataGridEx}}, Mode=OneWay}"> <Grid.RowDefinitions>
<CheckBox.Style> <RowDefinition Height="Auto" />
<Style TargetType="CheckBox" BasedOn="{StaticResource DataGridExCheckBoxStyle}"> <RowDefinition Height="*" />
<Setter Property="Visibility" Value="Collapsed" /> <RowDefinition Height="Auto" />
<Style.Triggers> </Grid.RowDefinitions>
<MultiDataTrigger> <Border
<MultiDataTrigger.Conditions> Grid.Row="0"
<Condition Binding="{Binding ShowCheckBox, RelativeSource={RelativeSource AncestorType={x:Type ext:DataGridEx}}}" Value="True" /> Grid.Column="0"
<Condition Binding="{Binding ShowSelectAll, RelativeSource={RelativeSource AncestorType={x:Type ext:DataGridEx}}}" Value="True" /> Width="{Binding CellsPanelHorizontalOffset, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
</MultiDataTrigger.Conditions> Background="#eeeeee"
<Setter Property="Visibility" Value="Visible" /> BorderBrush="{Binding BorderBrush, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
</MultiDataTrigger> BorderThickness="0,0,1,1">
</Style.Triggers> <CheckBox
</Style> Width="16"
</CheckBox.Style>
</CheckBox>
</Border>
<DataGridColumnHeadersPresenter
x:Name="PART_ColumnHeadersPresenter"
Grid.Column="1"
Grid.ColumnSpan="2"
Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Column}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
<Grid
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2">
<ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" />
<Grid
x:Name="NoDataTipsGrid"
HorizontalAlignment="Center"
VerticalAlignment="Center"
IsHitTestVisible="False"
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="60" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<Path
Width="100"
Height="60"
Data="M156.662278 699.758173h21.097186A10.444152 10.444152 0 0 1 187.994733 710.202325c0 5.765172-4.490985 10.444152-10.235269 10.444152H156.662278v21.097186A10.444152 10.444152 0 0 1 146.218126 751.978932a10.277045 10.277045 0 0 1-10.444152-10.235269V720.646477H114.676787A10.444152 10.444152 0 0 1 104.441518 710.202325c0-5.765172 4.490985-10.444152 10.235269-10.444152H135.773974v-21.097187A10.444152 10.444152 0 0 1 146.218126 668.425717c5.765172 0 10.444152 4.490985 10.444152 10.235269v21.097187z m1378.628042-83.553215v-21.097186A10.277045 10.277045 0 0 0 1524.846168 584.872503a10.444152 10.444152 0 0 0-10.444152 10.235269v21.097186h-21.097186a10.277045 10.277045 0 0 0-10.235269 10.444152c0 5.598065 4.595427 10.444152 10.235269 10.444152h21.097186v21.097187c0 5.744284 4.67898 10.235269 10.444152 10.235268a10.444152 10.444152 0 0 0 10.444152-10.235268V637.093262h21.097187c5.744284 0 10.235269-4.67898 10.235268-10.444152a10.444152 10.444152 0 0 0-10.235268-10.444152H1535.29032zM776.460024 960.861969H250.596979A20.80475 20.80475 0 0 1 229.77134 939.973665c0-11.530344 9.462402-20.888304 20.825639-20.888303h94.728457A83.010119 83.010119 0 0 1 334.212859 877.413196v-605.96969A83.49055 83.49055 0 0 1 417.849627 187.994733H480.430984V167.001988A83.49055 83.49055 0 0 1 564.067752 83.553215h501.152182A83.448773 83.448773 0 0 1 1148.856702 167.001988v605.969689c0 15.185797-4.052331 29.410732-11.133466 41.672166h115.554096c11.551232 0 20.909192 9.274407 20.909192 20.888304 0 11.530344-9.295295 20.888304-20.888304 20.888304H1002.638576v20.992745c0 15.185797-4.052331 29.410732-11.133466 41.672166h11.196131c11.488567 0 20.825639 9.274407 20.825639 20.888303 0 11.530344-9.462402 20.888304-20.825639 20.888304h-109.893365c9.545955 16.000441 7.478013 36.972297-6.41271 50.863019a41.672166 41.672166 0 0 1-59.072122 0L776.460024 960.861969z m76.367638-41.776607h66.424806c22.977134 0 41.609501-18.59059 41.609501-41.881049V270.461756c0-22.559368-18.047494-40.690416-40.314426-40.690416H416.303892c-22.266932 0-40.314426 18.214601-40.314426 40.690416v606.742557c0 23.123352 18.799473 41.881049 41.588613 41.881049h317.084449l-10.736588-10.757477a41.693054 41.693054 0 0 1-10.861918-40.377091l-19.718558-19.739447A146.259902 146.259902 0 0 1 502.363703 627.693525a146.218126 146.218126 0 0 1 220.517822 190.981761l19.739447 19.739447a41.630389 41.630389 0 0 1 40.377091 10.841029L852.827662 919.085362zM1002.638576 814.643843h62.852906A41.797496 41.797496 0 0 0 1107.080095 772.867236V167.106429c0-23.14424-18.632367-41.776607-41.588613-41.776607H563.775316A41.797496 41.797496 0 0 0 522.207592 167.106429v20.888304h396.794216A83.448773 83.448773 0 0 1 1002.638576 271.443506V814.643843zM266.325872 46.998683h31.123572c8.773088 0 15.875111 6.955805 15.875111 15.666228 0 8.647758-7.102023 15.666228-15.875111 15.666228h-31.123572v31.123572c0 8.773088-6.955805 15.875111-15.666228 15.875111a15.770669 15.770669 0 0 1-15.666228-15.875111V78.331139H203.869844A15.728893 15.728893 0 0 1 187.994733 62.664911c0-8.647758 7.102023-15.666228 15.875111-15.666228h31.123572V15.875111c0-8.773088 6.955805-15.875111 15.666228-15.875111 8.647758 0 15.666228 7.102023 15.666228 15.875111v31.123572zM20.888304 939.973665c0-11.530344 9.462402-20.888304 20.825638-20.888303h125.455152c11.488567 0 20.825639 9.274407 20.825639 20.888303 0 11.530344-9.462402 20.888304-20.825639 20.888304H41.713942A20.80475 20.80475 0 0 1 20.888304 939.973665z m658.733544-135.021995a104.441518 104.441518 0 1 0-147.722083-147.722083 104.441518 104.441518 0 0 0 147.722083 147.722083zM459.542681 313.324555a20.888304 20.888304 0 0 1 20.867415-20.888304H710.202325a20.888304 20.888304 0 1 1 0 41.776608H480.430984A20.825639 20.825639 0 0 1 459.542681 313.324555z m0 104.441518c0-11.530344 9.295295-20.888304 20.742085-20.888303h334.505295c11.44679 0 20.742086 9.274407 20.742086 20.888303 0 11.530344-9.295295 20.888304-20.742086 20.888304H480.284766A20.762974 20.762974 0 0 1 459.542681 417.766073z m0 104.441519c0-11.530344 9.316183-20.888304 20.846527-20.888304h146.301679c11.509455 0 20.846527 9.274407 20.846527 20.888304 0 11.530344-9.316183 20.888304-20.846527 20.888303h-146.301679A20.80475 20.80475 0 0 1 459.542681 522.207592zM62.664911 396.87777a62.664911 62.664911 0 1 1 0-125.329822 62.664911 62.664911 0 0 1 0 125.329822z m0-31.332456a31.332456 31.332456 0 1 0 0-62.664911 31.332456 31.332456 0 0 0 0 62.664911zM1357.739739 271.547948a62.664911 62.664911 0 1 1 0-125.329822 62.664911 62.664911 0 0 1 0 125.329822z m0-31.332456a31.332456 31.332456 0 1 0 0-62.664911 31.332456 31.332456 0 0 0 0 62.664911z"
Fill="LightGray"
Stretch="Fill" />
<TextBlock
Grid.Row="1"
Margin="10"
HorizontalAlignment="Center" HorizontalAlignment="Center"
VerticalAlignment="Bottom" VerticalAlignment="Center"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=FontSize, Mode=OneWay}" HorizontalContentAlignment="Center"
Foreground="LightGray" Command="{x:Static ext:DataGridEx.ToggleSelectAllCommand}"
Text="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=(f:DataGridHelper.NoDataTips), Mode=OneWay}" /> CommandTarget="{Binding RelativeSource={RelativeSource AncestorType={x:Type ext:DataGridEx}}}"
IsChecked="{Binding AreAllRowsSelected, RelativeSource={RelativeSource AncestorType={x:Type ext:DataGridEx}}, Mode=OneWay}">
<CheckBox.Style>
<Style BasedOn="{StaticResource DataGridExCheckBoxStyle}" TargetType="CheckBox">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ShowCheckBox, RelativeSource={RelativeSource AncestorType={x:Type ext:DataGridEx}}}" Value="True" />
<Condition Binding="{Binding ShowSelectAll, RelativeSource={RelativeSource AncestorType={x:Type ext:DataGridEx}}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter Property="Visibility" Value="Visible" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
</CheckBox.Style>
</CheckBox>
</Border>
<DataGridColumnHeadersPresenter
x:Name="PART_ColumnHeadersPresenter"
Grid.Column="1"
Grid.ColumnSpan="2"
Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Column}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
<Grid
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2">
<ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" />
<Grid
x:Name="NoDataTipsGrid"
HorizontalAlignment="Center"
VerticalAlignment="Center"
IsHitTestVisible="False"
Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="60" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<Path
Width="100"
Height="60"
Data="M156.662278 699.758173h21.097186A10.444152 10.444152 0 0 1 187.994733 710.202325c0 5.765172-4.490985 10.444152-10.235269 10.444152H156.662278v21.097186A10.444152 10.444152 0 0 1 146.218126 751.978932a10.277045 10.277045 0 0 1-10.444152-10.235269V720.646477H114.676787A10.444152 10.444152 0 0 1 104.441518 710.202325c0-5.765172 4.490985-10.444152 10.235269-10.444152H135.773974v-21.097187A10.444152 10.444152 0 0 1 146.218126 668.425717c5.765172 0 10.444152 4.490985 10.444152 10.235269v21.097187z m1378.628042-83.553215v-21.097186A10.277045 10.277045 0 0 0 1524.846168 584.872503a10.444152 10.444152 0 0 0-10.444152 10.235269v21.097186h-21.097186a10.277045 10.277045 0 0 0-10.235269 10.444152c0 5.598065 4.595427 10.444152 10.235269 10.444152h21.097186v21.097187c0 5.744284 4.67898 10.235269 10.444152 10.235268a10.444152 10.444152 0 0 0 10.444152-10.235268V637.093262h21.097187c5.744284 0 10.235269-4.67898 10.235268-10.444152a10.444152 10.444152 0 0 0-10.235268-10.444152H1535.29032zM776.460024 960.861969H250.596979A20.80475 20.80475 0 0 1 229.77134 939.973665c0-11.530344 9.462402-20.888304 20.825639-20.888303h94.728457A83.010119 83.010119 0 0 1 334.212859 877.413196v-605.96969A83.49055 83.49055 0 0 1 417.849627 187.994733H480.430984V167.001988A83.49055 83.49055 0 0 1 564.067752 83.553215h501.152182A83.448773 83.448773 0 0 1 1148.856702 167.001988v605.969689c0 15.185797-4.052331 29.410732-11.133466 41.672166h115.554096c11.551232 0 20.909192 9.274407 20.909192 20.888304 0 11.530344-9.295295 20.888304-20.888304 20.888304H1002.638576v20.992745c0 15.185797-4.052331 29.410732-11.133466 41.672166h11.196131c11.488567 0 20.825639 9.274407 20.825639 20.888303 0 11.530344-9.462402 20.888304-20.825639 20.888304h-109.893365c9.545955 16.000441 7.478013 36.972297-6.41271 50.863019a41.672166 41.672166 0 0 1-59.072122 0L776.460024 960.861969z m76.367638-41.776607h66.424806c22.977134 0 41.609501-18.59059 41.609501-41.881049V270.461756c0-22.559368-18.047494-40.690416-40.314426-40.690416H416.303892c-22.266932 0-40.314426 18.214601-40.314426 40.690416v606.742557c0 23.123352 18.799473 41.881049 41.588613 41.881049h317.084449l-10.736588-10.757477a41.693054 41.693054 0 0 1-10.861918-40.377091l-19.718558-19.739447A146.259902 146.259902 0 0 1 502.363703 627.693525a146.218126 146.218126 0 0 1 220.517822 190.981761l19.739447 19.739447a41.630389 41.630389 0 0 1 40.377091 10.841029L852.827662 919.085362zM1002.638576 814.643843h62.852906A41.797496 41.797496 0 0 0 1107.080095 772.867236V167.106429c0-23.14424-18.632367-41.776607-41.588613-41.776607H563.775316A41.797496 41.797496 0 0 0 522.207592 167.106429v20.888304h396.794216A83.448773 83.448773 0 0 1 1002.638576 271.443506V814.643843zM266.325872 46.998683h31.123572c8.773088 0 15.875111 6.955805 15.875111 15.666228 0 8.647758-7.102023 15.666228-15.875111 15.666228h-31.123572v31.123572c0 8.773088-6.955805 15.875111-15.666228 15.875111a15.770669 15.770669 0 0 1-15.666228-15.875111V78.331139H203.869844A15.728893 15.728893 0 0 1 187.994733 62.664911c0-8.647758 7.102023-15.666228 15.875111-15.666228h31.123572V15.875111c0-8.773088 6.955805-15.875111 15.666228-15.875111 8.647758 0 15.666228 7.102023 15.666228 15.875111v31.123572zM20.888304 939.973665c0-11.530344 9.462402-20.888304 20.825638-20.888303h125.455152c11.488567 0 20.825639 9.274407 20.825639 20.888303 0 11.530344-9.462402 20.888304-20.825639 20.888304H41.713942A20.80475 20.80475 0 0 1 20.888304 939.973665z m658.733544-135.021995a104.441518 104.441518 0 1 0-147.722083-147.722083 104.441518 104.441518 0 0 0 147.722083 147.722083zM459.542681 313.324555a20.888304 20.888304 0 0 1 20.867415-20.888304H710.202325a20.888304 20.888304 0 1 1 0 41.776608H480.430984A20.825639 20.825639 0 0 1 459.542681 313.324555z m0 104.441518c0-11.530344 9.295295-20.888304 20.742085-20.888303h334.505295c11.44679 0 20.742086 9.274407 20.742086 20.888303 0 11.530344-9.295295 20.888304-20.742086 20.888304H480.284766A20.762974 20.762974 0 0 1 459.542681 417.766073z m0 104.441519c0-11.530344 9.316183-20.888304 20.846527-20.888304h146.301679c11.509455 0 20.846527 9.274407 20.846527 20.888304 0 11.530344-9.316183 20.888304-20.846527 20.888303h-146.301679A20.80475 20.80475 0 0 1 459.542681 522.207592zM62.664911 396.87777a62.664911 62.664911 0 1 1 0-125.329822 62.664911 62.664911 0 0 1 0 125.329822z m0-31.332456a31.332456 31.332456 0 1 0 0-62.664911 31.332456 31.332456 0 0 0 0 62.664911zM1357.739739 271.547948a62.664911 62.664911 0 1 1 0-125.329822 62.664911 62.664911 0 0 1 0 125.329822z m0-31.332456a31.332456 31.332456 0 1 0 0-62.664911 31.332456 31.332456 0 0 0 0 62.664911z"
Fill="LightGray"
Stretch="Fill" />
<TextBlock
Grid.Row="1"
Margin="10"
HorizontalAlignment="Center"
VerticalAlignment="Bottom"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=FontSize, Mode=OneWay}"
Foreground="LightGray"
Text="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=(f:DataGridHelper.NoDataTips), Mode=OneWay}" />
</Grid>
</Grid>
<ScrollBar
x:Name="PART_VerticalScrollBar"
Grid.Row="1"
Grid.Column="2"
Maximum="{TemplateBinding ScrollableHeight}"
Orientation="Vertical"
ViewportSize="{TemplateBinding ViewportHeight}"
Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"
Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" />
<Grid
Grid.Row="2"
Grid.Column="0"
Grid.ColumnSpan="2">
<ScrollBar
x:Name="PART_HorizontalScrollBar"
Maximum="{TemplateBinding ScrollableWidth}"
Orientation="Horizontal"
ViewportSize="{TemplateBinding ViewportWidth}"
Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"
Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" />
</Grid> </Grid>
</Grid> </Grid>
<ScrollBar <ControlTemplate.Triggers>
x:Name="PART_VerticalScrollBar" <MultiDataTrigger>
Grid.Row="1" <MultiDataTrigger.Conditions>
Grid.Column="2" <Condition Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=(f:DataGridHelper.IsActive)}" Value="false" />
Maximum="{TemplateBinding ScrollableHeight}" <Condition Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=HasItems}" Value="false" />
Orientation="Vertical" </MultiDataTrigger.Conditions>
<Setter TargetName="NoDataTipsGrid" Property="Visibility" Value="Visible" />
ViewportSize="{TemplateBinding ViewportHeight}" </MultiDataTrigger>
Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" <!--<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=(f:DataGridHelper.NoDataTips)}" Value="{x:Null}">
Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" />
<Grid Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2">
<ScrollBar
x:Name="PART_HorizontalScrollBar"
Maximum="{TemplateBinding ScrollableWidth}"
Orientation="Horizontal"
ViewportSize="{TemplateBinding ViewportWidth}"
Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"
Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" />
</Grid>
</Grid>
<ControlTemplate.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=(f:DataGridHelper.IsActive)}" Value="false" />
<Condition Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=HasItems}" Value="false" />
</MultiDataTrigger.Conditions>
<Setter TargetName="NoDataTipsGrid" Property="Visibility" Value="Visible" />
</MultiDataTrigger>
<!--<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=(f:DataGridHelper.NoDataTips)}" Value="{x:Null}">
<Setter TargetName="NoDataTipsGrid" Property="Visibility" Value="Collapsed" /> <Setter TargetName="NoDataTipsGrid" Property="Visibility" Value="Collapsed" />
</DataTrigger> </DataTrigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=(f:DataGridHelper.NoDataTips)}" Value=""> <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=(f:DataGridHelper.NoDataTips)}" Value="">
<Setter TargetName="NoDataTipsGrid" Property="Visibility" Value="Collapsed" /> <Setter TargetName="NoDataTipsGrid" Property="Visibility" Value="Collapsed" />
</DataTrigger>--> </DataTrigger>-->
</ControlTemplate.Triggers> </ControlTemplate.Triggers>
</ControlTemplate> </ControlTemplate>
</ScrollViewer.Template> </ScrollViewer.Template>
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /> <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</ScrollViewer> </ScrollViewer>
</Border> </Border>
<!-- 分页仅请求数据,不截断调用方的 ItemsSource。 --> <!-- 分页仅请求数据,不截断调用方的 ItemsSource。 -->
<Border x:Name="PART_PaginationArea" Grid.Row="2" Background="#FAFAFA" BorderBrush="#E1E4E8" BorderThickness="1,0,1,1" Padding="8,4" <Border
Visibility="{Binding ShowPagination, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay, Converter={StaticResource DataGridExVisibility}}"> x:Name="PART_PaginationArea"
<Grid> Grid.Row="2"
<ContentPresenter x:Name="PART_PaginationContent" Content="{TemplateBinding PaginationContent}"/> Padding="8,4"
<DockPanel x:Name="PART_DefaultPagination" Visibility="Collapsed"> Background="#FAFAFA"
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal"> BorderBrush="{TemplateBinding BorderBrush}"
<TextBlock Text="每页" VerticalAlignment="Center" Margin="0,0,6,0"/> BorderThickness="{Binding BorderThickness, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource DataGridExBorderThicknessSplit}, ConverterParameter='1,0,1,1'}"
<ComboBox Width="70" MinHeight="26" IsEditable="False" Margin="0,0,8,0" Visibility="{Binding ShowPagination, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay, Converter={StaticResource DataGridExVisibility}}">
ItemsSource="{Binding PageSizes, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" <Grid>
SelectedItem="{Binding PageSize, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> <ContentPresenter x:Name="PART_PaginationContent" Content="{TemplateBinding PaginationContent}" />
<Button Content="首页" Command="{x:Static local:DataGridEx.FirstPageCommand}" Padding="8,2" Margin="0,0,4,0"/> <DockPanel x:Name="PART_DefaultPagination" Visibility="Collapsed">
<Button Content="上一页" Command="{x:Static local:DataGridEx.PreviousPageCommand}" Padding="8,2"/> <StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
<TextBlock Text="{Binding PageSummary, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" VerticalAlignment="Center" Margin="10,0"/> <TextBlock
<Button Content="下一页" Command="{x:Static local:DataGridEx.NextPageCommand}" Padding="8,2"/> Margin="0,0,6,0"
<Button Content="末页" Command="{x:Static local:DataGridEx.LastPageCommand}" Padding="8,2" Margin="4,0,0,0"/> VerticalAlignment="Center"
</StackPanel> Text="每页" />
<TextBlock Text="{Binding TotalSummary, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" VerticalAlignment="Center"/> <ComboBox
</DockPanel> Width="70"
</Grid> MinHeight="26"
</Border> Margin="0,0,8,0"
<Border x:Name="PART_LoadingOverlay" Grid.RowSpan="3" Background="#DDFFFFFF" Visibility="Collapsed" Cursor="Wait"> IsEditable="False"
<StackPanel Width="180" HorizontalAlignment="Center" VerticalAlignment="Center"> ItemsSource="{Binding PageSizes, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}"
<ProgressBar x:Name="PART_LoadingProgress" Height="4" IsIndeterminate="False" Foreground="#98638F" Background="#EDE5EB" BorderThickness="0"/> SelectedItem="{Binding PageSize, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="{TemplateBinding LoadingText}" HorizontalAlignment="Center" Margin="0,12,0,0" Foreground="#626873" <Button
AutomationProperties.LiveSetting="Polite"/> Margin="0,0,4,0"
</StackPanel> Padding="8,2"
</Border> Command="{x:Static local:DataGridEx.FirstPageCommand}"
</Grid> Content="首页" />
<ControlTemplate.Triggers> <Button
<Trigger Property="IsLoading" Value="True"> Padding="8,2"
<Setter TargetName="PART_LoadingOverlay" Property="Visibility" Value="Visible"/> Command="{x:Static local:DataGridEx.PreviousPageCommand}"
<Setter TargetName="PART_LoadingProgress" Property="IsIndeterminate" Value="True"/> Content="上一页" />
<Setter TargetName="PART_ToolbarArea" Property="IsEnabled" Value="False"/> <TextBlock
<Setter TargetName="PART_TableArea" Property="IsEnabled" Value="False"/> Margin="10,0"
<Setter TargetName="PART_PaginationArea" Property="IsEnabled" Value="False"/> VerticalAlignment="Center"
</Trigger> Text="{Binding PageSummary, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" />
<Trigger Property="PaginationContent" Value="{x:Null}"> <Button
<Setter TargetName="PART_DefaultPagination" Property="Visibility" Value="Visible"/> Padding="8,2"
<Setter TargetName="PART_PaginationContent" Property="Visibility" Value="Collapsed"/> Command="{x:Static local:DataGridEx.NextPageCommand}"
</Trigger> Content="下一页" />
</ControlTemplate.Triggers> <Button
</ControlTemplate> Margin="4,0,0,0"
Padding="8,2"
Command="{x:Static local:DataGridEx.LastPageCommand}"
Content="末页" />
</StackPanel>
<TextBlock VerticalAlignment="Center" Text="{Binding TotalSummary, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" />
</DockPanel>
</Grid>
</Border>
<Border
x:Name="PART_LoadingOverlay"
Grid.RowSpan="3"
Background="#DDFFFFFF"
Cursor="Wait"
Visibility="Collapsed">
<StackPanel
Width="180"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<ProgressBar
x:Name="PART_LoadingProgress"
Height="4"
Background="#EDE5EB"
BorderThickness="0"
Foreground="#98638F"
IsIndeterminate="False" />
<TextBlock
Margin="0,12,0,0"
HorizontalAlignment="Center"
AutomationProperties.LiveSetting="Polite"
Foreground="#626873"
Text="{TemplateBinding LoadingText}" />
</StackPanel>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsLoading" Value="True">
<Setter TargetName="PART_LoadingOverlay" Property="Visibility" Value="Visible" />
<Setter TargetName="PART_LoadingProgress" Property="IsIndeterminate" Value="True" />
<Setter TargetName="PART_ToolbarArea" Property="IsEnabled" Value="False" />
<Setter TargetName="PART_TableArea" Property="IsEnabled" Value="False" />
<Setter TargetName="PART_PaginationArea" Property="IsEnabled" Value="False" />
</Trigger>
<Trigger Property="PaginationContent" Value="{x:Null}">
<Setter TargetName="PART_DefaultPagination" Property="Visibility" Value="Visible" />
<Setter TargetName="PART_PaginationContent" Property="Visibility" Value="Collapsed" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value> </Setter.Value>
</Setter> </Setter>
<Style.Triggers> <Style.Triggers>
@@ -704,8 +819,8 @@
</Setter> </Setter>
</Style> </Style>
<Style x:Key="DataGridExRowStyle" TargetType="{x:Type DataGridRow}"> <Style x:Key="DataGridExRowStyle" TargetType="{x:Type DataGridRow}">
<Setter Property="ContextMenu" Value="{Binding RowContextMenu, RelativeSource={RelativeSource AncestorType=local:DataGridEx}}" /> <Setter Property="ContextMenu" Value="{Binding RowContextMenu, RelativeSource={RelativeSource AncestorType=local:DataGridEx}}" />
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=local:DataGridEx}}" /> <Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=local:DataGridEx}}" />
<Setter Property="BorderThickness" Value="0,0,1,0" /> <Setter Property="BorderThickness" Value="0,0,1,0" />
<Setter Property="Background" Value="Transparent" /> <Setter Property="Background" Value="Transparent" />
<Setter Property="FontSize" Value="{StaticResource DataGridExFontSize}" /> <Setter Property="FontSize" Value="{StaticResource DataGridExFontSize}" />
@@ -739,7 +854,8 @@
Grid.Column="1" Grid.Column="1"
SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical}, Converter={x:Static DataGrid.RowDetailsScrollingConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical}, Converter={x:Static DataGrid.RowDetailsScrollingConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
Visibility="{TemplateBinding DetailsVisibility}" /> Visibility="{TemplateBinding DetailsVisibility}" />
<DataGridRowHeader x:Name="PART_RowHeader" <DataGridRowHeader
x:Name="PART_RowHeader"
Grid.RowSpan="2" Grid.RowSpan="2"
SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical" SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" /> Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
@@ -838,18 +954,27 @@
</Setter.Value> </Setter.Value>
</Setter> </Setter>
</Style> </Style>
<Style x:Key="DataGridExRowHeaderStyle" BasedOn="{StaticResource DataGridExDefaultRowHeaderStyle}" TargetType="DataGridRowHeader"> <Style
<Setter Property="Template"> x:Key="DataGridExRowHeaderStyle"
<Setter.Value> BasedOn="{StaticResource DataGridExDefaultRowHeaderStyle}"
<ControlTemplate TargetType="DataGridRowHeader"> TargetType="DataGridRowHeader">
<Border Background="Transparent" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="0,0,1,1"> <Setter Property="Template">
<CheckBox Style="{StaticResource DataGridExCheckBoxStyle}" HorizontalAlignment="Center" VerticalAlignment="Center" AutomationProperties.Name="选择行" <Setter.Value>
IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> <ControlTemplate TargetType="DataGridRowHeader">
</Border> <Border
</ControlTemplate> Background="Transparent"
</Setter.Value> BorderBrush="{TemplateBinding BorderBrush}"
</Setter> BorderThickness="0,0,1,1">
</Style> <CheckBox
HorizontalAlignment="Center"
VerticalAlignment="Center"
IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource DataGridExCheckBoxStyle}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style <Style
x:Key="DataGridExNumberCellStyle" x:Key="DataGridExNumberCellStyle"
@@ -858,12 +983,15 @@
<Setter Property="HorizontalContentAlignment" Value="Right" /> <Setter Property="HorizontalContentAlignment" Value="Right" />
</Style> </Style>
<Style BasedOn="{StaticResource DataGridExDefaultDataGridStyle}" TargetType="local:DataGridEx"> <Style
<Setter Property="EnableRowVirtualization" Value="True" /> x:Key="DataGridExBaseStyle"
<Setter Property="EnableColumnVirtualization" Value="True" /> BasedOn="{StaticResource DataGridExDefaultDataGridStyle}"
<Setter Property="VirtualizingPanel.IsVirtualizing" Value="True" /> TargetType="local:DataGridEx">
<Setter Property="VirtualizingPanel.VirtualizationMode" Value="Recycling" /> <Setter Property="EnableRowVirtualization" Value="True" />
<Setter Property="ScrollViewer.CanContentScroll" Value="True" /> <Setter Property="EnableColumnVirtualization" Value="True" />
<Setter Property="VirtualizingPanel.IsVirtualizing" Value="True" />
<Setter Property="VirtualizingPanel.VirtualizationMode" Value="Recycling" />
<Setter Property="ScrollViewer.CanContentScroll" Value="True" />
<Setter Property="SelectionMode" Value="Extended" /> <Setter Property="SelectionMode" Value="Extended" />
<Setter Property="SelectionUnit" Value="FullRow" /> <Setter Property="SelectionUnit" Value="FullRow" />
@@ -872,4 +1000,5 @@
<Setter Property="RowHeaderStyle" Value="{StaticResource DataGridExRowHeaderStyle}" /> <Setter Property="RowHeaderStyle" Value="{StaticResource DataGridExRowHeaderStyle}" />
</Style> </Style>
<Style BasedOn="{StaticResource DataGridExBaseStyle}" TargetType="local:DataGridEx" />
</ResourceDictionary> </ResourceDictionary>
@@ -1,12 +1,13 @@
<local:WindowBase x:Class="Store.Management.Framework.Controls.DialogWindow" <local:WindowBase
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" x:Class="Store.Management.Framework.Controls.DialogWindow"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Store.Management.Framework.Controls" xmlns:local="clr-namespace:Store.Management.Framework.Controls"
mc:Ignorable="d" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="DialogWindow" Height="450" Width="800"> Title="{Binding Title}"
<Grid> Width="800"
Height="450"
</Grid> mc:Ignorable="d">
<Grid />
</local:WindowBase> </local:WindowBase>
@@ -1,6 +1,4 @@
using MAX.Framework.Controls;
using MAX.Framework.Controls.Attach;
using Prism.Services.Dialogs; using Prism.Services.Dialogs;
using Store.Management.Framework.Controls; using Store.Management.Framework.Controls;
using Store.Management.Framework.Controls.Attach; using Store.Management.Framework.Controls.Attach;
@@ -91,6 +89,8 @@ public partial class DialogWindow : WindowBase, IDialogWindow
if (newContent is UserControl control) if (newContent is UserControl control)
{ {
WindowStartupLocation = DialogWindowProperty.GetWindowStartupLocation(control);
Setter widthSetter = this.Style.Setters.OfType<Setter>().FirstOrDefault(a => a.Property == WidthProperty); Setter widthSetter = this.Style.Setters.OfType<Setter>().FirstOrDefault(a => a.Property == WidthProperty);
if (widthSetter == null) if (widthSetter == null)
{ {
@@ -0,0 +1,127 @@
using MAX.Common.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace Store.Management.Framework.Controls
{
internal class HorizontalIconText : Control
{
public string Icon
{
get => (string)GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
public static readonly DependencyProperty IconProperty = DependencyProperty.Register(
nameof(Icon),
typeof(string),
typeof(HorizontalIconText),
new PropertyMetadata(null, OnOnIconChanged)
);
public bool ShowIcon
{
get => (bool)GetValue(ShowIconProperty);
private set => SetValue(ShowIconPropertyKey, value);
}
private static readonly DependencyPropertyKey ShowIconPropertyKey = DependencyProperty.RegisterReadOnly(
nameof(ShowIcon),
typeof(bool),
typeof(HorizontalIconText),
new PropertyMetadata(false)
);
public static readonly DependencyProperty ShowIconProperty = ShowIconPropertyKey.DependencyProperty;
public bool ShowSpace
{
get => (bool)GetValue(ShowSpaceProperty);
private set => SetValue(ShowSpacePropertyKey, value);
}
private static readonly DependencyPropertyKey ShowSpacePropertyKey = DependencyProperty.RegisterReadOnly(
nameof(ShowSpace),
typeof(bool),
typeof(HorizontalIconText),
new PropertyMetadata(true)
);
public static readonly DependencyProperty ShowSpaceProperty = ShowSpacePropertyKey.DependencyProperty;
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
nameof(Text),
typeof(string),
typeof(HorizontalIconText),
new PropertyMetadata(string.Empty)
);
public double IconSize
{
get => (double)GetValue(IconSizeProperty);
set => SetValue(IconSizeProperty, value);
}
public static readonly DependencyProperty IconSizeProperty = DependencyProperty.Register(
nameof(IconSize),
typeof(double),
typeof(HorizontalIconText),
new PropertyMetadata(14d)
);
public double Spacing
{
get => (double)GetValue(SpacingProperty);
set => SetValue(SpacingProperty, value);
}
public static readonly DependencyProperty SpacingProperty = DependencyProperty.Register(
nameof(Spacing),
typeof(double),
typeof(HorizontalIconText),
new PropertyMetadata(4d)
);
private static void OnOnIconChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is HorizontalIconText view)
{
view.ShowIcon = view.Icon.IsNotBlank();
}
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property == ShowSpaceProperty)
{
return;
}
ShowSpace = ShowIcon && Text.IsNotBlank();
}
}
}
@@ -0,0 +1,42 @@
using PipeReviewReport.Resources.Fonts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace Store.Management.Framework.Controls
{
public class IconText : TextBlock
{
static IconText()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(IconText), new FrameworkPropertyMetadata(typeof(IconText)));
}
public IconNameEnum Icon
{
get => (IconNameEnum)GetValue(IconNameProperty);
set => SetValue(IconNameProperty, value);
}
public static readonly DependencyProperty IconNameProperty = DependencyProperty.Register(
nameof(Icon),
typeof(IconNameEnum),
typeof(IconText),
new PropertyMetadata(IconNameEnum.Empty, OnIconChanged)
);
private static void OnIconChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is IconText self)
{
self.Text = self.Icon.GetGlyphString();
}
}
}
}
@@ -0,0 +1,85 @@
using Prism.Services.Dialogs;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace Store.Management.Framework.Controls;
internal static class ViewLifecycle
{
// 卸载时 DataContext 可能已改变,记录实际收到 OnLoaded 的实例。
private static readonly DependencyProperty LoadedViewModelProperty =
DependencyProperty.RegisterAttached("LoadedViewModel", typeof(ViewModelBase), typeof(ViewLifecycle));
internal static void Register()
{
foreach (Type type in new[] { typeof(UserControl), typeof(Window) })
{
FrameworkElement.DataContextProperty.OverrideMetadata(type,
new FrameworkPropertyMetadata(null, OnDataContextChanged));
}
}
private static void OnDataContextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (sender is Window window)
{
if (e.OldValue is ViewModelBase)
{
window.Activated -= OnActivated;
window.Deactivated -= OnDeactivated;
window.Closing -= OnClosing;
window.Closed -= OnClosed;
}
if (e.NewValue is ViewModelBase)
{
window.Activated += OnActivated;
window.Deactivated += OnDeactivated;
window.Closing += OnClosing;
window.Closed += OnClosed;
}
if (window is IDialogWindow) return; // Prism 弹窗由内容页接收加载与卸载。
}
var view = (FrameworkElement)sender;
if (e.OldValue is ViewModelBase)
{
view.Loaded -= OnLoaded;
view.Unloaded -= OnUnloaded;
}
if (e.NewValue is ViewModelBase)
{
view.Loaded += OnLoaded;
view.Unloaded += OnUnloaded;
}
if (view.IsLoaded || view.GetValue(LoadedViewModelProperty) != null)
UpdateViewModel(view);
}
private static void OnLoaded(object sender, RoutedEventArgs e)
=> UpdateViewModel((FrameworkElement)sender);
private static void OnActivated(object? sender, EventArgs e) => (((Window)sender!).DataContext as ViewModelBase)?.OnActivated();
private static void OnDeactivated(object? sender, EventArgs e) => (((Window)sender!).DataContext as ViewModelBase)?.OnDeactivated();
private static void OnClosing(object? sender, CancelEventArgs e) => (((Window)sender!).DataContext as ViewModelBase)?.OnClosing(e);
private static void OnClosed(object? sender, EventArgs e) => (((Window)sender!).DataContext as ViewModelBase)?.OnClosed();
private static void UpdateViewModel(FrameworkElement view)
{
// 共享父级 DataContext 的页眉、导航栏等子控件不拥有页面生命周期。
var source = DependencyPropertyHelper.GetValueSource(view, FrameworkElement.DataContextProperty);
var next = source.BaseValueSource == BaseValueSource.Inherited ? null : view.DataContext as ViewModelBase;
var previous = (ViewModelBase?)view.GetValue(LoadedViewModelProperty);
if (ReferenceEquals(previous, next)) return;
view.SetValue(LoadedViewModelProperty, next);
previous?.OnUnloaded();
next?.NotifyLoaded();
}
private static void OnUnloaded(object sender, RoutedEventArgs e)
{
var view = (FrameworkElement)sender;
var previous = (ViewModelBase?)view.GetValue(LoadedViewModelProperty);
view.ClearValue(LoadedViewModelProperty);
previous?.OnUnloaded();
}
}
@@ -0,0 +1,28 @@
using Prism.Mvvm;
using System.ComponentModel;
namespace Store.Management.Framework.Controls;
public abstract class ViewModelBase : BindableBase
{
private bool hasLoaded;
internal void NotifyLoaded()
{
if (!hasLoaded)
{
hasLoaded = true;
OnLoadedOnce();
}
OnLoaded();
}
/// <summary>当前实例首次加载时调用,先于 OnLoaded。</summary>
protected virtual void OnLoadedOnce() { }
protected internal virtual void OnLoaded() { }
protected internal virtual void OnUnloaded() { }
protected internal virtual void OnActivated() { }
protected internal virtual void OnDeactivated() { }
protected internal virtual void OnClosing(CancelEventArgs e) { }
protected internal virtual void OnClosed() { }
}
@@ -1,8 +1,10 @@
using MAX.Common.Helpers;
using MAX.Framework.Logger; using MAX.Framework.Logger;
using NLog; using NLog;
using Prism.Autofac; using Prism.Autofac;
using Prism.Ioc; using Prism.Ioc;
using Prism.Services.Dialogs; using Prism.Services.Dialogs;
using Store.Management.Api;
using Store.Management.Framework.Configs; using Store.Management.Framework.Configs;
using Store.Management.Framework.Extensions; using Store.Management.Framework.Extensions;
using Store.Management.Framework.Services; using Store.Management.Framework.Services;
@@ -14,137 +16,157 @@ namespace Store.Management.Framework;
public abstract class FrameworkApplication : PrismApplication public abstract class FrameworkApplication : PrismApplication
{ {
private Mutex? _mutex; private Mutex? _mutex;
private bool _ownsMutex; private bool _ownsMutex;
private int _fatalHandling; private int _fatalHandling;
private int _shutdownRequested; private int _shutdownRequested;
public static bool ShuttingDown { get; private set; } public static bool ShuttingDown { get; private set; }
public static bool IsAppInitialized { get; private set; } public static bool IsAppInitialized { get; private set; }
public static event Action<Exception>? FatalErrorRaised; public static event Action<Exception>? FatalErrorRaised;
private IStatusBarService StatusBarService;
private IMessageBoxService MessageBoxService;
private static bool FatalShutdown = false;
static FrameworkApplication() => Controls.ViewLifecycle.Register();
protected FrameworkApplication() protected FrameworkApplication()
{ {
DispatcherUnhandledException += OnDispatcherUnhandledException; DispatcherUnhandledException += OnDispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += OnDomainUnhandledException; AppDomain.CurrentDomain.UnhandledException += OnDomainUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException; TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
} }
/// <summary>返回 null 可允许多开;默认限制同一登录会话中的应用实例。</summary> /// <summary>返回 null 可允许多开;默认限制同一登录会话中的应用实例。</summary>
public virtual string? GetMutexName() => @"Local\Store.Management"; public virtual string? GetMutexName() => @"Local\Store.Management";
protected override void OnStartup(StartupEventArgs e) protected override void OnStartup(StartupEventArgs e)
{ {
try try
{ {
//string? name = GetMutexName(); //string? name = GetMutexName();
//if (!string.IsNullOrWhiteSpace(name)) //if (!string.IsNullOrWhiteSpace(name))
//{ //{
// _mutex = new Mutex(true, name, out _ownsMutex); // _mutex = new Mutex(true, name, out _ownsMutex);
// if (!_ownsMutex) // if (!_ownsMutex)
// { // {
// MessageBox.Show("程序已在运行。", Config.AppName, MessageBoxButton.OK, MessageBoxImage.Information); // MessageBox.Show("程序已在运行。", Config.AppName, MessageBoxButton.OK, MessageBoxImage.Information);
// Shutdown(); // Shutdown();
// return; // return;
// } // }
//} //}
FolderConfig.Initialize(); FolderConfig.Initialize();
base.OnStartup(e); base.OnStartup(e);
ApplicationLogService.Initialize(); ApplicationLogService.Initialize();
NLogger.Instance.Info($"软件启动:{Config.AppFullName},版本:{Config.GetFullVersionString()},会话:{Config.SessionID},启动时间:{Config.AppStartTime:O},Windows:{Config.WindowsVersion}"); NLogger.Instance.Info($"软件启动:{Config.AppFullName},版本:{Config.GetFullVersionString()},会话:{Config.SessionID},启动时间:{Config.AppStartTime:O},Windows:{Config.WindowsVersion}");
DISource.Resolver = Resolve; DISource.Resolver = Resolve;
} }
catch (Exception ex) { Fatal(ex); } catch (Exception ex) { Fatal(ex); }
} }
protected override void OnInitialized() protected override void OnInitialized()
{ {
base.OnInitialized(); base.OnInitialized();
IsAppInitialized = true; IsAppInitialized = true;
NLogger.Instance.Info("软件初始化成功,进入主页面"); NLogger.Instance.Info("软件初始化成功,进入主页面");
} StatusBarService = Container?.Resolve<IStatusBarService>();
MessageBoxService = Container?.Resolve<IMessageBoxService>();
}
protected override void RegisterRequiredTypes(IContainerRegistry registry) protected override void RegisterRequiredTypes(IContainerRegistry registry)
{ {
base.RegisterRequiredTypes(registry); base.RegisterRequiredTypes(registry);
registry.RegisterDialogWindow<Controls.DialogWindow>(); registry.RegisterDialogWindow<Controls.DialogWindow>();
} }
private object Resolve(Type type, string name) private object Resolve(Type type, string name)
{ {
if (type == null || Container is null) return null!; if (type == null || Container is null) return null!;
return name != null ? Container.Resolve(type, name) : Container.Resolve(type); return name != null ? Container.Resolve(type, name) : Container.Resolve(type);
} }
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{ {
e.Handled = true; e.Handled = true;
Fatal(e.Exception); StatusBarService.Report(e.Exception.Message, StatusLevel.Error);
} Fatal(e.Exception);
private void OnDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) }
{
Exception exception = e.ExceptionObject as Exception ?? new Exception(e.ExceptionObject?.ToString());
// CLR 终止期间同步记录,不等待 UI 线程。
if (e.IsTerminating) ApplicationLogService.WriteFatal(exception, "AppDomain.UnhandledException");
else Fatal(exception);
}
private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e) private void OnDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{ {
ApplicationLogService.WriteFatal(e.Exception, "TaskScheduler.UnobservedTaskException"); Exception exception = e.ExceptionObject as Exception ?? new Exception(e.ExceptionObject?.ToString());
e.SetObserved(); StatusBarService.Report(exception.Message, StatusLevel.Error);
} // CLR 终止期间同步记录,不等待 UI 线程。
if (e.IsTerminating) ApplicationLogService.WriteFatal(exception, "AppDomain.UnhandledException");
else Fatal(exception);
}
/// <summary>先同步保存报告,再通知订阅者并关闭应用。</summary> private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
public static void Fatal(Exception exception) {
{ ApplicationLogService.WriteFatal(e.Exception, "TaskScheduler.UnobservedTaskException");
ArgumentNullException.ThrowIfNull(exception); e.SetObserved();
string? path = ApplicationLogService.WriteFatal(exception, "Fatal"); }
if (Current is not FrameworkApplication app || Interlocked.Exchange(ref app._fatalHandling, 1) != 0) return;
foreach (Action<Exception> handler in FatalErrorRaised?.GetInvocationList() ?? [])
{
try { handler(exception); }
catch (Exception ex) { ApplicationLogService.WriteFatal(ex, "FatalErrorRaised"); }
}
void ShowErrorAndShutdown()
{
try
{
MessageBox.Show($"软件发生致命错误,即将关闭。\n{exception.Message}\n\n日志:{path ?? "写入失败,请查看调试输出"}",
Config.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
}
finally { TotalShutdown(-1); }
}
if (app.Dispatcher.CheckAccess()) ShowErrorAndShutdown();
else if (!app.Dispatcher.HasShutdownStarted) app.Dispatcher.BeginInvoke((Action)ShowErrorAndShutdown);
}
/// <summary>通过 WPF 正常退出,执行退出清理。</summary> /// <summary>先同步保存报告,再通知订阅者并关闭应用。</summary>
public static void TotalShutdown(int exitCode = 0) public void Fatal(Exception exception)
{ {
if (Current is not FrameworkApplication app || Interlocked.Exchange(ref app._shutdownRequested, 1) != 0) return; ArgumentNullException.ThrowIfNull(exception);
ShuttingDown = true; string? path = ApplicationLogService.WriteFatal(exception, "Fatal");
if (app.Dispatcher.CheckAccess()) app.Shutdown(exitCode); if (Current is not FrameworkApplication app || Interlocked.Exchange(ref app._fatalHandling, 1) != 0) return;
else if (!app.Dispatcher.HasShutdownStarted) app.Dispatcher.BeginInvoke((Action)(() => app.Shutdown(exitCode))); foreach (Action<Exception> handler in FatalErrorRaised?.GetInvocationList() ?? [])
} {
try { handler(exception); }
catch (Exception ex) { ApplicationLogService.WriteFatal(ex, "FatalErrorRaised"); }
}
void ShowErrorAndShutdown()
{
if (FatalShutdown)
{
try
{
MessageBox.Show($"软件发生致命错误,即将关闭。\n{exception.Message}\n\n日志:{path ?? "写入失败,请查看调试输出"}",
Config.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
}
finally { TotalShutdown(-1); }
}
else
{
MessageBoxService.ShowError(exception.Message);
}
}
if (app.Dispatcher.CheckAccess()) ShowErrorAndShutdown();
else if (!app.Dispatcher.HasShutdownStarted) app.Dispatcher.BeginInvoke((Action)ShowErrorAndShutdown);
}
protected override void OnExit(ExitEventArgs e) /// <summary>通过 WPF 正常退出,执行退出清理。</summary>
{ public static void TotalShutdown(int exitCode = 0)
ShuttingDown = true; {
try { base.OnExit(e); } if (Current is not FrameworkApplication app || Interlocked.Exchange(ref app._shutdownRequested, 1) != 0) return;
finally ShuttingDown = true;
{ if (app.Dispatcher.CheckAccess()) app.Shutdown(exitCode);
DispatcherUnhandledException -= OnDispatcherUnhandledException; else if (!app.Dispatcher.HasShutdownStarted) app.Dispatcher.BeginInvoke((Action)(() => app.Shutdown(exitCode)));
AppDomain.CurrentDomain.UnhandledException -= OnDomainUnhandledException; }
TaskScheduler.UnobservedTaskException -= OnUnobservedTaskException;
DISource.Resolver = null!; protected override void OnExit(ExitEventArgs e)
try { if (_ownsMutex) _mutex?.ReleaseMutex(); } {
finally ShuttingDown = true;
{ try
_mutex?.Dispose(); {
try { NLogger.Instance.Info($"软件关闭,退出码:{e.ApplicationExitCode}"); } try { Container?.Resolve<StoreApiClient>().Dispose(); }
finally { LogManager.Shutdown(); } finally { base.OnExit(e); }
} }
} finally
} {
DispatcherUnhandledException -= OnDispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException -= OnDomainUnhandledException;
TaskScheduler.UnobservedTaskException -= OnUnobservedTaskException;
DISource.Resolver = null!;
try { if (_ownsMutex) _mutex?.ReleaseMutex(); }
finally
{
_mutex?.Dispose();
try { NLogger.Instance.Info($"软件关闭,退出码:{e.ApplicationExitCode}"); }
finally { LogManager.Shutdown(); }
}
}
}
} }
@@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.ComponentModel;
namespace Store.Management.Framework.Interfaces
{
public interface IMessageBoxService
{
//MessageResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageIcon icon, MessageResult defaultResult);
}
}
@@ -0,0 +1,11 @@
using Riok.Mapperly.Abstractions;
using Store.Management.Framework.ViewModels;
using Store.Management.Models;
namespace Store.Management.Framework.Mappers;
[Mapper]
public static partial class ShopMapper
{
public static partial IReadOnlyList<ShopItemViewModel> ToItemViewModels(IReadOnlyList<ShopInfo> shops);
}
@@ -0,0 +1,12 @@
using Riok.Mapperly.Abstractions;
using Store.Management.Framework.ViewModels;
using Store.Management.Models;
namespace Store.Management.Framework.Mappers;
[Mapper]
public static partial class UserMapper
{
public static partial UserItemViewModel ToItemViewModel(UserInfo user);
public static partial IReadOnlyList<UserItemViewModel> ToItemViewModels(IReadOnlyList<UserInfo> users);
}
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Management.Framework
{
public class Navigation
{
public static string MainContext { get; } = nameof(MainContext);
}
}
@@ -0,0 +1,68 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="LightPrimaryColor">#F4EDF3</Color>
<Color x:Key="PrimaryColor">#98638F</Color>
<Color x:Key="DarkPrimaryColor">#784B70</Color>
<Color x:Key="LightDangerColor">#FBEFF0</Color>
<Color x:Key="DangerColor">#C35C64</Color>
<Color x:Key="DarkDangerColor">#A34A52</Color>
<Color x:Key="LightWarningColor">#FBF4E7</Color>
<Color x:Key="WarningColor">#A77725</Color>
<Color x:Key="DarkWarningColor">#855D1B</Color>
<Color x:Key="LightInfoColor">#F0F2F4</Color>
<Color x:Key="InfoColor">#69727D</Color>
<Color x:Key="DarkInfoColor">#59616B</Color>
<Color x:Key="LightSuccessColor">#EAF5F0</Color>
<Color x:Key="SuccessColor">#31856A</Color>
<Color x:Key="DarkSuccessColor">#276B55</Color>
<Color x:Key="PrimaryTextColor">#292731</Color>
<Color x:Key="SecondaryTextColor">#7C838C</Color>
<Color x:Key="ThirdlyTextColor">#A0A6AD</Color>
<Color x:Key="ReverseTextColor">#FFFFFF</Color>
<Color x:Key="TextIconColor">#FFFFFF</Color>
<Color x:Key="BorderColor">#E5E7EB</Color>
<Color x:Key="SecondaryBorderColor">#D1D5DB</Color>
<Color x:Key="BackgroundColor">#F5F6F7</Color>
<Color x:Key="RegionColor">#FFFFFF</Color>
<Color x:Key="SecondaryRegionColor">#F0F2F4</Color>
<Color x:Key="ThirdlyRegionColor">#FAFBFC</Color>
<Color x:Key="TitleColor">#98638F</Color>
<Color x:Key="SecondaryTitleColor">#784B70</Color>
<Color x:Key="DefaultColor">#FFFFFF</Color>
<Color x:Key="DarkDefaultColor">#F0F2F4</Color>
<Color x:Key="AccentColor">#98638F</Color>
<Color x:Key="DarkAccentColor">#784B70</Color>
<Color x:Key="DarkMaskColor">#20000000</Color>
<Color x:Key="DarkOpacityColor">#40000000</Color>
<SolidColorBrush x:Key="SelectedBackgroundBrush" Color="#F3EAF1" />
<SolidColorBrush x:Key="SelectedForegroundBrush" Color="#784B70" />
<Color x:Key="BackgrondColor1">#F7F8F9</Color>
<Color x:Key="BackgrondColor2">#F0F2F4</Color>
<Color x:Key="BackgrondColor3">#E5E7EB</Color>
<Color x:Key="BackgrondColor4">#D1D5DB</Color>
<SolidColorBrush x:Key="Background1" Color="{StaticResource BackgrondColor1}" />
<SolidColorBrush x:Key="Background2" Color="{StaticResource BackgrondColor2}" />
<SolidColorBrush x:Key="Background3" Color="{StaticResource BackgrondColor3}" />
<SolidColorBrush x:Key="Background4" Color="{StaticResource BackgrondColor4}" />
<Color x:Key="FunctionTypeColor">#98638F</Color>
<Color x:Key="VariableTypeColor">#31856A</Color>
<Color x:Key="ConstTypeColor">#A77725</Color>
<SolidColorBrush x:Key="FunctionTypeBrush" Color="{StaticResource FunctionTypeColor}" />
<SolidColorBrush x:Key="VariableTypeBrush" Color="{StaticResource VariableTypeColor}" />
<SolidColorBrush x:Key="ConstTypeBrush" Color="{StaticResource ConstTypeColor}" />
</ResourceDictionary>
@@ -0,0 +1,65 @@
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ output extension=".xaml" encoding="utf-8" #>
<#
StringBuilder FontString = new StringBuilder();
FontString.AppendLine("<ResourceDictionary");
FontString.AppendLine("\txmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"");
FontString.AppendLine("\txmlns:PresentationOptions=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation/options\"");
FontString.AppendLine("\txmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"");
FontString.AppendLine("\txmlns:sys=\"clr-namespace:System;assembly=mscorlib\"");
FontString.AppendLine("\t>");
FontString.AppendLine("");
FontString.AppendLine("");
string cssPath = this.Host.ResolvePath("iconfont.css");
string svgPath = this.Host.ResolvePath("iconfont.js");
if (File.Exists(cssPath))
{
string cssContent = File.ReadAllText(cssPath, Encoding.UTF8);
MatchCollection matchs = Regex.Matches(cssContent, "\\.icon-(?<name>.+?):before.+?\\{.+?content:.+?\"\\\\(?<value>e.+?)\";.+?\\}", RegexOptions.Singleline);
foreach (Match match in matchs)
{
string name = match.Groups["name"].Value;
//name = Regex.Replace(name,"(a-(\\d{4,}(.*)?_fluent_|SegoeFluentIconsRegular-))|(_regular_icon|$)","",RegexOptions.Singleline);
string value = match.Groups["value"].Value;
FontString.AppendLine(string.Format("\t<sys:String x:Key=\"txt-{0}\">&#x{1};</sys:String>", name, value));
}
}
if (File.Exists(svgPath))
{
FontString.AppendLine("");
FontString.AppendLine("");
string svgContent = File.ReadAllText(svgPath, Encoding.UTF8);
MatchCollection matchs = Regex.Matches(svgContent, "<symbol.+?id=\"(?<name>.+?)\".+?>(?<value>.+?)</symbol>");
foreach (Match match in matchs)
{
string name = match.Groups["name"].Value;
string symbol = match.Groups["value"].Value;
StringBuilder value =new StringBuilder();
MatchCollection pathMatchs = Regex.Matches(symbol,"<path.+?d=\"(?<value>.+?)\"");
foreach(Match pathMatch in pathMatchs)
{
value.AppendLine("\t\t"+pathMatch.Groups["value"].Value);
}
FontString.AppendLine(string.Format("\t<Geometry x:Key=\"{0}\" PresentationOptions:Freeze=\"True\">\n{1}\t</Geometry>", name, value));
}
}
FontString.AppendLine("");
FontString.AppendLine("");
FontString.AppendLine("</ResourceDictionary>");
string content = FontString.ToString();
string savePath =Path.Combine(this.Host.ResolvePath(""),@"..\Themes\FontGeometry.xaml");
//File.WriteAllText(savePath,content,Encoding.UTF8);
#>
<#=content#>
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,284 @@
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#@ assembly name="$(ProjectDir)\Resources\DLLs\IconResourcesGenerator.dll" #>
<#@ import namespace="IconResourcesGenerator" #>
<#@ output extension=".cs" encoding="utf-8" #>
<#
ITextTemplatingEngineHost host = this.Host;
string jsPath = host.ResolvePath("iconfont.js");
string cssPath = host.ResolvePath("iconfont.css");
string namespaceName = "PipeReviewReport.Resources.Fonts";
Generator generator = new Generator(jsPath, cssPath);
Dictionary<string, string> glyphToKey = generator.ExecuteGlyphToKey();
Dictionary<string, string> keyToGlyph = generator.ExecuteKeyToGlyph();
(Dictionary<string, string> simpleNameToKey, Dictionary<string, string> keyToSimpleName) = generator.ExecuteSimpleNameToKey();
#>
using System;
// using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace <#= namespaceName #>;
[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
internal class __________________Temp__________________
{
[SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "<Pending>")]
private void Test()
{
}
};
/// <summary>
/// 图标名称枚举
/// </summary>
// [TypeConverter(typeof(EnumConverter))]
public enum IconNameEnum
{
Empty,
<#
foreach (var entry in simpleNameToKey)
{
#>
/// <summary>
/// <#= keyToGlyph[entry.Value] #>
/// <br/>
/// icon-<#= entry.Value #>
/// </summary>
<#= entry.Key #>,
<#
}
#>
}
public static class IconNameEnumExtensions
{
/// <summary>
/// 根据图标名称枚举获取 Key
/// </summary>
/// <param name="e">图标名称枚举</param>
/// <returns>注册到资源中的 Key</returns>
/// <exception cref="NotImplementedException"></exception>
public static string GetKey(this IconNameEnum e) {
return e switch
{
IconNameEnum.Empty => null,
<#
foreach (var entry in simpleNameToKey)
{
#>
IconNameEnum.<#= entry.Key #> => "icon-<#= entry.Value #>",
<#
}
#>
_ => throw new NotImplementedException(),
};
}
/// <summary>
/// 根据图标名称获取 Glyph 枚举
/// </summary>
/// <param name="e">图标名称枚举</param>
/// <returns>图标 Glyph 枚举</returns>
/// <exception cref="NotImplementedException"></exception>
public static IconGlyphEnum GetGlyphEnum(this IconNameEnum e) {
return e switch
{
IconNameEnum.Empty => IconGlyphEnum.Empty,
<#
foreach (var entry in simpleNameToKey)
{
#>
IconNameEnum.<#= entry.Key #> => IconGlyphEnum.<#= keyToGlyph[entry.Value] #>,
<#
}
#>
_ => throw new NotImplementedException(),
};
}
/// <summary>
/// 根据图标名称获取 Glyph 字符串
/// </summary>
/// <param name="e">图标名称枚举</param>
/// <returns>图标 Glyph 字符串</returns>
/// <exception cref="NotImplementedException"></exception>
public static string GetGlyphString(this IconNameEnum e) {
return e switch
{
IconNameEnum.Empty => string.Empty,
<#
foreach (var entry in simpleNameToKey)
{
#>
IconNameEnum.<#= entry.Key #> => "\u<#= keyToGlyph[entry.Value] #>",
<#
}
#>
_ => throw new NotImplementedException(),
};
}
public static string GetImageSourceKey(this IconNameEnum e) {
return GetKey(e) + "_Image";
}
}
/// <summary>
/// 图标 Glyph 枚举
/// </summary>
// [TypeConverter(typeof(EnumConverter))]
public enum IconGlyphEnum
{
Empty,
<#
foreach (var entry in glyphToKey)
{
#>
/// <summary>
/// <#= keyToSimpleName[entry.Value] #>
/// <br/>
/// icon-<#= entry.Value #>
/// </summary>
<#= entry.Key #>,
<#
}
#>
}
public static class IconGlyphEnumExtensions
{
/// <summary>
/// 根据 Glyph 枚举获取 Key
/// </summary>
/// <param name="e">Glyph 枚举</param>
/// <returns>注册到资源中的 Key</returns>
/// <exception cref="NotImplementedException"></exception>
public static string GetKey(this IconGlyphEnum e)
{
return e switch
{
IconGlyphEnum.Empty => null,
<#
foreach (var entry in glyphToKey)
{
#>
IconGlyphEnum.<#= entry.Key #> => "icon-<#= entry.Value #>",
<#
}
#>
_ => throw new NotImplementedException(),
};
}
/// <summary>
/// 根据图标 Glyph 枚举获取图标名称枚举
/// </summary>
/// <param name="e">图标 Glyph 枚举</param>
/// <returns>图标名称枚举</returns>
/// <exception cref="NotImplementedException"></exception>
public static IconNameEnum GetNameEnum(this IconGlyphEnum e) {
return e switch
{
IconGlyphEnum.Empty => IconNameEnum.Empty,
<#
foreach (var entry in glyphToKey)
{
#>
IconGlyphEnum.<#= entry.Key #> => IconNameEnum.<#= keyToSimpleName[entry.Value] #>,
<#
}
#>
_ => throw new NotImplementedException(),
};
}
/// <summary>
/// 根据图标 Glyph 枚举获取 Glyph 字符串
/// </summary>
/// <param name="e">图标 Glyph 枚举</param>
/// <returns>图标 Glyph 字符串</returns>
/// <exception cref="NotImplementedException"></exception>
public static string GetGlyphString(this IconGlyphEnum e) {
return e switch
{
IconGlyphEnum.Empty => string.Empty,
<#
foreach (var entry in glyphToKey)
{
#>
IconGlyphEnum.<#= entry.Key #> => "\u<#= keyToGlyph[entry.Value] #>",
<#
}
#>
_ => throw new NotImplementedException(),
};
}
public static string GetImageSourceKey(this IconGlyphEnum e) {
return GetKey(e) + "_Image";
}
}
public class IconEnumNameToGlyphConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is IconNameEnum nameEnum) {
return nameEnum.GetGlyphEnum();
}
return DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is IconGlyphEnum glyphEnum) {
return glyphEnum.GetNameEnum();
}
return DependencyProperty.UnsetValue;
}
}
public class IconGlyphNameToNameConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is IconGlyphEnum glyphEnum) {
return glyphEnum.GetNameEnum();
}
return DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is IconNameEnum nameEnum) {
return nameEnum.GetGlyphEnum();
}
return DependencyProperty.UnsetValue;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
window._iconfont_svg_string_5223831='<svg><symbol id="icon-fapiao" viewBox="0 0 1024 1024"><path d="M170.666667 868.693333l98.346666-94.72a21.333333 21.333333 0 0 1 30.72 1.173334l98.176 110.122666 98.176-110.122666a21.333333 21.333333 0 0 1 31.829334 0l98.176 110.122666 98.176-110.122666a21.333333 21.333333 0 0 1 30.72-1.173334L853.333333 868.693333V128H170.666667v740.693333z m-42.666667 49.386667V106.709333C128 94.890667 137.706667 85.333333 149.333333 85.333333h725.333334c11.776 0 21.333333 9.642667 21.333333 21.184v811.541334a21.333333 21.333333 0 0 1-36.117333 16.149333l-118.506667-114.133333-99.349333 111.445333a21.333333 21.333333 0 0 1-31.850667 0L512 821.397333l-98.176 110.122667a21.333333 21.333333 0 0 1-31.850667 0l-99.349333-111.445333-118.485333 114.133333A21.333333 21.333333 0 0 1 128 918.08zM298.666667 320c0-11.776 9.493333-21.333333 21.184-21.333333h341.632c11.690667 0 21.184 9.472 21.184 21.333333 0 11.776-9.493333 21.333333-21.184 21.333333H319.850667A21.205333 21.205333 0 0 1 298.666667 320z m0 128c0-11.776 9.6-21.333333 21.482666-21.333333h255.701334c11.861333 0 21.482667 9.472 21.482666 21.333333 0 11.776-9.6 21.333333-21.482666 21.333333H320.149333A21.354667 21.354667 0 0 1 298.666667 448z m0 128c0-11.776 9.6-21.333333 21.482666-21.333333h255.701334c11.861333 0 21.482667 9.472 21.482666 21.333333 0 11.776-9.6 21.333333-21.482666 21.333333H320.149333A21.354667 21.354667 0 0 1 298.666667 576z" fill="#3D3D3D" ></path></symbol><symbol id="icon-calendar_work_week" viewBox="0 0 1024 1024"><path d="M330.666667 298.666667a32 32 0 0 0-32 32v170.666666c0 17.664 14.336 32 32 32h362.666666a32 32 0 0 0 32-32v-170.666666a32 32 0 0 0-32-32h-362.666666z m32 170.666666V362.666667h298.666666V469.333333h-298.666666z" ></path><path d="M757.333333 896A138.666667 138.666667 0 0 0 896 757.333333V266.666667A138.666667 138.666667 0 0 0 757.333333 128H266.666667A138.666667 138.666667 0 0 0 128 266.666667v490.666666A138.666667 138.666667 0 0 0 266.666667 896h490.666666zM832 266.666667v490.666666a74.666667 74.666667 0 0 1-74.666667 74.666667H266.666667a74.666667 74.666667 0 0 1-74.666667-74.666667V266.666667c0-41.216 33.450667-74.666667 74.666667-74.666667h490.666666c41.216 0 74.666667 33.450667 74.666667 74.666667z" ></path></symbol><symbol id="icon-document_endnote" viewBox="0 0 1024 1024"><path d="M234.666667 181.333333a32 32 0 0 1 32-32H512V341.333333a85.333333 85.333333 0 0 0 85.333333 85.333334h192v416a32 32 0 0 1-32 32H554.666667V938.666667h202.666666A96 96 0 0 0 853.333333 842.666667V412.330667c0-19.797333-7.850667-38.784-21.888-52.778667l-252.330666-252.330667A74.666667 74.666667 0 0 0 526.336 85.333333H266.666667A96 96 0 0 0 170.666667 181.333333V512h64V181.333333z m341.333333 160V194.56l168.106667 168.106667H597.333333a21.333333 21.333333 0 0 1-21.333333-21.333334zM192 586.666667a32 32 0 0 1-32 32H106.666667v298.666666h53.333333a32 32 0 0 1 0 64H106.666667A64 64 0 0 1 42.666667 917.333333v-298.666666A64 64 0 0 1 106.666667 554.666667h53.333333a32 32 0 0 1 32 32z" ></path><path d="M394.666667 618.666667a32 32 0 0 1 0-64h53.333333a64 64 0 0 1 64 64v298.666666a64 64 0 0 1-64 64H394.666667a32 32 0 0 1 0-64h53.333333v-298.666666H394.666667zM277.333333 714.666667a32 32 0 0 1 32 32V896a32 32 0 0 1-64 0v-149.333333a32 32 0 0 1 32-32zM277.333333 682.666667a32 32 0 1 0 0-64 32 32 0 0 0 0 64z" ></path></symbol><symbol id="icon-leaf_three" viewBox="0 0 1024 1024"><path d="M810.666667 320c0 22.186667-3.072 43.648-8.832 64h69.12C908.373333 384 938.666667 414.293333 938.666667 451.669333V661.333333a277.333333 277.333333 0 0 1-449.493334 217.429334L438.613333 929.28a32 32 0 1 1-45.226666-45.226667l50.517333-50.56a277.077333 277.077333 0 0 1-40.704-70.613333A256 256 0 0 1 96 512V320.597333C96 284.928 124.928 256 160.597333 256h189.568A234.752 234.752 0 0 1 576 85.333333h173.226667c33.92 0 61.44 27.52 61.44 61.44V320zM414.805333 263.765333a256.554667 256.554667 0 0 1 165.504 132.266667A277.290667 277.290667 0 0 1 661.333333 384h72.96c7.978667-19.754667 12.373333-41.386667 12.373334-64v-170.666667h-170.666667a170.752 170.752 0 0 0-161.194667 114.432z m120.021334 569.344A213.333333 213.333333 0 0 0 874.666667 661.333333v-209.664a3.669333 3.669333 0 0 0-3.669334-3.669333H661.333333a213.333333 213.333333 0 0 0-171.776 339.84l181.162667-181.12a32 32 0 1 1 45.226667 45.226667l-181.12 181.162666zM384 661.333333c0-25.258667 3.413333-49.749333 9.728-73.002666L276.053333 470.613333a32 32 0 1 1 45.226667-45.226666l98.901333 98.858666a278.698667 278.698667 0 0 1 101.333334-102.485333A192 192 0 0 0 352 320H160.384l-0.213333 0.170667a0.938667 0.938667 0 0 0-0.128 0.213333l-0.042667 0.213333V512a192 192 0 0 0 226.816 188.842667A279.765333 279.765333 0 0 1 384 661.333333z" ></path></symbol><symbol id="icon-re_order_dots_horizontal" viewBox="0 0 1024 1024"><path d="M298.666667 661.333333a64 64 0 1 1-128 0 64 64 0 0 1 128 0z m0-298.666666a64 64 0 1 1-128 0 64 64 0 0 1 128 0z m298.666666 298.666666a64 64 0 1 1-128 0 64 64 0 0 1 128 Line truncated
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,291 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ResourceDictionary
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:f="clr-namespace:Store.Management.Framework.Controls"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wpf="MAX.WPF"
mc:Ignorable="d">
<ResourceDictionary.MergedDictionaries> <ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Fonts/FontGeometry.xaml" />
<ResourceDictionary Source="pack://application:,,,/MAX.Common.WPF;component/Resources/Generic.xaml" />
<ResourceDictionary Source="/Store.Management.Framework;component/Controls/DataGridEx/DataGridEx.xaml" /> <ResourceDictionary Source="/Store.Management.Framework;component/Controls/DataGridEx/DataGridEx.xaml" />
</ResourceDictionary.MergedDictionaries> </ResourceDictionary.MergedDictionaries>
<Style
x:Key="IconButtonStyle"
BasedOn="{StaticResource ButtonCustom}"
TargetType="Button">
<Setter Property="Width" Value="32" />
<Setter Property="Height" Value="28" />
<Setter Property="Padding" Value="0" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Cursor" Value="Hand" />
</Style>
<!-- 表格搜索区:统一尺寸,窄窗口允许换行。 -->
<Style x:Key="TableSearchTextBoxStyle" BasedOn="{StaticResource TextBoxExtend}" TargetType="TextBox">
<Setter Property="Width" Value="180" />
<Setter Property="Height" Value="32" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
<Style x:Key="TableSearchComboBoxStyle" BasedOn="{StaticResource {x:Type ComboBox}}" TargetType="ComboBox">
<Setter Property="Width" Value="180" />
<Setter Property="Height" Value="32" />
</Style>
<Style x:Key="TableSearchButtonStyle" BasedOn="{StaticResource {x:Type Button}}" TargetType="Button">
<Setter Property="Width" Value="80" />
<Setter Property="Height" Value="32" />
<Setter Property="Padding" Value="8,0" />
</Style>
<Style x:Key="TableSearchPrimaryButtonStyle" BasedOn="{StaticResource ButtonPrimary}" TargetType="Button">
<Setter Property="Width" Value="80" />
<Setter Property="Height" Value="32" />
<Setter Property="Padding" Value="8,0" />
</Style>
<Style x:Key="TableSearchBarStyle" TargetType="wpf:SpacingStackPanel">
<Style.Resources>
<Style BasedOn="{StaticResource TableSearchTextBoxStyle}" TargetType="TextBox" />
<Style BasedOn="{StaticResource TableSearchComboBoxStyle}" TargetType="ComboBox" />
<Style BasedOn="{StaticResource TableSearchButtonStyle}" TargetType="Button" />
</Style.Resources>
<Setter Property="MinHeight" Value="44" />
<Setter Property="Margin" Value="10,0" />
<Setter Property="Orientation" Value="Horizontal" />
<Setter Property="ChildWrapping" Value="True" />
<Setter Property="HorizontalSpacing" Value="8" />
<Setter Property="VerticalSpacing" Value="8" />
<Setter Property="ItemVerticalAlignment" Value="Center" />
</Style>
<FontFamily x:Key="IconPack">Fonts/iconfont.ttf#iconfont</FontFamily>
<Style BasedOn="{StaticResource DataGridExBaseStyle}" TargetType="{x:Type f:DataGridEx}">
<Setter Property="SelectedRowBackground" Value="{DynamicResource SelectedBackgroundBrush}" />
<Setter Property="SelectedRowForeground" Value="{DynamicResource SelectedForegroundBrush}" />
</Style>
<Style x:Key="TextBlockIcon" TargetType="{x:Type TextBlock}">
<Setter Property="FontFamily" Value="{StaticResource IconPack}" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="FontSize" Value="18" />
</Style>
<Style BasedOn="{StaticResource TextBlockIcon}" TargetType="{x:Type f:IconText}" />
<Style BasedOn="{StaticResource {x:Type MenuItem}}" TargetType="{x:Type MenuItem}">
<Setter Property="Width" Value="200" />
<Style.Resources>
<Style BasedOn="{StaticResource TextBlockIcon}" TargetType="{x:Type f:IconText}">
<Setter Property="FontSize" Value="16" />
</Style>
</Style.Resources>
</Style>
<Style
x:Key="WindowBase"
BasedOn="{StaticResource WindowWin10}"
TargetType="f:WindowBase">
<Setter Property="Background" Value="White" />
</Style>
<Style
x:Key="DialogWindowStyle"
BasedOn="{StaticResource WindowBase}"
TargetType="f:DialogWindow">
<Setter Property="Tag" Value="Default" />
<Setter Property="ResizeMode" Value="NoResize" />
<Setter Property="ShowInTaskbar" Value="False" />
<Setter Property="WindowChrome.GlassFrameThickness" Value="-1" />
</Style>
<Style BasedOn="{StaticResource WindowBase}" TargetType="f:WindowBase" />
<Style BasedOn="{StaticResource DialogWindowStyle}" TargetType="f:DialogWindow" />
<!--<Style x:Key="HorizontalSpacingPanel" TargetType="hc:UniformSpacingPanel">
<Setter Property="Orientation" Value="Horizontal" />
<Setter Property="HorizontalSpacing" Value="2" />
<Setter Property="ItemVerticalAlignment" Value="Center" />
</Style>-->
<!--<Style x:Key="HorizontalSpacingPanel2" TargetType="hc:UniformSpacingPanel">
<Setter Property="Orientation" Value="Horizontal" />
<Setter Property="HorizontalSpacing" Value="4" />
<Setter Property="ItemVerticalAlignment" Value="Center" />
</Style>
<Style x:Key="VerticalSpacingPanel" TargetType="hc:UniformSpacingPanel">
<Setter Property="Orientation" Value="Vertical" />
<Setter Property="VerticalSpacing" Value="2" />
</Style>
<Style x:Key="VerticalSpacingPanel2" TargetType="hc:UniformSpacingPanel">
<Setter Property="Orientation" Value="Vertical" />
<Setter Property="VerticalSpacing" Value="4" />
</Style>-->
<Style x:Key="HorizontalSpacingPanel" TargetType="wpf:SpacingStackPanel">
<Setter Property="Orientation" Value="Horizontal" />
<Setter Property="HorizontalSpacing" Value="2" />
<Setter Property="ItemVerticalAlignment" Value="Center" />
</Style>
<Style x:Key="HorizontalSpacingPanel4" TargetType="wpf:SpacingStackPanel">
<Setter Property="Orientation" Value="Horizontal" />
<Setter Property="HorizontalSpacing" Value="4" />
<Setter Property="ItemVerticalAlignment" Value="Center" />
</Style>
<Style x:Key="HorizontalSpacingPanel8" TargetType="wpf:SpacingStackPanel">
<Setter Property="Orientation" Value="Horizontal" />
<Setter Property="HorizontalSpacing" Value="8" />
<Setter Property="ItemVerticalAlignment" Value="Center" />
</Style>
<Style x:Key="VerticalSpacingPanel" TargetType="wpf:SpacingStackPanel">
<Setter Property="Orientation" Value="Vertical" />
<Setter Property="VerticalSpacing" Value="2" />
</Style>
<Style x:Key="VerticalSpacingPanel4" TargetType="wpf:SpacingStackPanel">
<Setter Property="Orientation" Value="Vertical" />
<Setter Property="VerticalSpacing" Value="4" />
</Style>
<Style x:Key="VerticalSpacingPanel8" TargetType="wpf:SpacingStackPanel">
<Setter Property="Orientation" Value="Vertical" />
<Setter Property="VerticalSpacing" Value="8" />
</Style>
<Style
x:Key="HorizontalIconText"
BasedOn="{StaticResource BaseStyle}"
TargetType="f:HorizontalIconText">
<Setter Property="Spacing" Value="4" />
<Setter Property="Focusable" Value="False" />
<Setter Property="IconSize" Value="16" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="f:HorizontalIconText">
<Border>
<DockPanel>
<TextBlock
FontSize="{TemplateBinding IconSize}"
Style="{StaticResource TextBlockIcon}"
Text="{TemplateBinding Icon}"
Visibility="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ShowIcon, Converter={StaticResource Boolean2VisibilityConverter}}" />
<Border Width="{TemplateBinding Spacing}" Visibility="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ShowSpace, Converter={StaticResource Boolean2VisibilityConverter}}" />
<TextBlock
VerticalAlignment="Center"
Text="{TemplateBinding Text}"
TextTrimming="CharacterEllipsis" />
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style BasedOn="{StaticResource HorizontalIconText}" TargetType="f:HorizontalIconText" />
<Style x:Key="Dialog" TargetType="UserControl">
<Setter Property="Padding" Value="0" />
<Setter Property="Focusable" Value="True" />
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="Background" Value="White" />
</Style>
<Style
x:Key="DialogButtonStyle"
BasedOn="{StaticResource ButtonDefault}"
TargetType="Button">
<Setter Property="MinWidth" Value="70" />
<Setter Property="Height" Value="26" />
</Style>
<Style
x:Key="DialogPrimaryButtonStyle"
BasedOn="{StaticResource ButtonPrimary}"
TargetType="Button">
<Setter Property="MinWidth" Value="70" />
<Setter Property="Height" Value="26" />
</Style>
<Style
x:Key="ConfirmDialog"
BasedOn="{StaticResource Dialog}"
TargetType="UserControl">
<Setter Property="Background" Value="White" />
<Setter Property="Padding" Value="10" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="UserControl">
<Border
d:DataContext="{d:DesignInstance Type=f:ConfirmDialogViewModel}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<Border Padding="{TemplateBinding Padding}">
<ContentPresenter />
</Border>
<Border
Grid.Row="1"
Padding="5,8"
BorderBrush="{StaticResource BorderBrush}"
BorderThickness="0,1,0,0">
<Grid>
<Border Padding="2,0">
<f:HorizontalIconText
d:Text="错误信息"
Foreground="{StaticResource DangerBrush}"
Icon="{StaticResource txt-warning}"
Text="{Binding ErrorMsg}"
Visibility="{Binding ErrorMsg, Converter={StaticResource String2VisibilityConverter}}" />
</Border>
<wpf:SpacingStackPanel HorizontalAlignment="Right" Style="{StaticResource HorizontalSpacingPanel4}">
<Button Command="{Binding ConfirmCommand}" Style="{StaticResource DialogPrimaryButtonStyle}">
<TextBlock Text="确认" />
</Button>
<Button
HorizontalAlignment="Right"
Command="{Binding CancelCommand}"
Style="{StaticResource DialogButtonStyle}">
<TextBlock Text="取消" />
</Button>
</wpf:SpacingStackPanel>
</Grid>
</Border>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style
x:Key="VerticalAlignment"
BasedOn="{StaticResource TitleContentBaseStyle}"
TargetType="wpf:TitleContent">
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="TitleVerticalAlignment" Value="Center" />
<Setter Property="Placement" Value="Left" />
</Style>
</ResourceDictionary> </ResourceDictionary>
@@ -0,0 +1,22 @@
using MAX.Core.DependencyInjection;
using Store.Management.Api;
using Store.Management.Api.Authentication;
namespace Store.Management.Framework.Services;
/// <summary>用户登录服务,复用应用 API 客户端的认证会话。</summary>
public interface ILoginService
{
/// <summary>提交登录;passwordHash 为 UTF-8 密码的 32 位大写 MD5。</summary>
Task LoginAsync(string userName, string passwordHash, CancellationToken cancellationToken = default);
}
internal sealed class LoginService(StoreApiClient apiClient) : ILoginService, ISingletonDependency
{
public Task LoginAsync(string userName, string passwordHash, CancellationToken cancellationToken = default)
=> apiClient.Auth.LoginAsync(new LoginRequest
{
UserName = userName.Trim(),
Password = passwordHash
}, cancellationToken);
}
@@ -0,0 +1,27 @@
using MAX.Core.Commons;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Store.Management.Framework
{
public interface IMessageBoxService
{
MessageResult Show(string messageBoxText, string caption, MessageButton button, MessageIcon icon, MessageResult defaultResult);
void ShowInformation(string content);
void ShowWarning(string content);
void ShowError(string content);
void ShowError(string content, Exception exception);
bool ShowYesNoQuestion(string content);
bool ShowYesNoWarning(string content);
bool ShowYesNoError(string content);
bool ShowOkCancelQuestion(string content);
bool ShowOkCancelWarning(string content);
bool ShowOkCancelError(string content);
MessageResult ShowYesNoCancelQuestion(string content);
MessageResult ShowYesNoCancelWarning(string content);
MessageResult ShowYesNoCancelError(string content);
}
}
@@ -0,0 +1,99 @@
using System.ComponentModel;
using System.Windows;
namespace Store.Management.Framework
{
public static class MessageBoxEnumsConverter
{
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static bool? ToBool(this MessageBoxResult result)
{
switch (result)
{
case MessageBoxResult.Cancel: return null;
case MessageBoxResult.No: return false;
default: return true;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static bool? ToBool(this MessageResult result)
{
switch (result)
{
case MessageResult.Cancel: return null;
case MessageResult.No: return false;
default: return true;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static MessageBoxResult ToMessageBoxResult(this MessageResult result)
{
switch (result)
{
case MessageResult.Cancel: return MessageBoxResult.Cancel;
case MessageResult.No: return MessageBoxResult.No;
case MessageResult.Yes: return MessageBoxResult.Yes;
case MessageResult.OK: return MessageBoxResult.OK;
default: return MessageBoxResult.None;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static MessageResult ToMessageResult(this MessageBoxResult result)
{
switch (result)
{
case MessageBoxResult.Cancel: return MessageResult.Cancel;
case MessageBoxResult.No: return MessageResult.No;
case MessageBoxResult.Yes: return MessageResult.Yes;
case MessageBoxResult.OK: return MessageResult.OK;
default: return MessageResult.None;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static MessageBoxButton ToMessageBoxButton(this MessageButton button)
{
switch (button)
{
case MessageButton.OKCancel: return MessageBoxButton.OKCancel;
case MessageButton.YesNo: return MessageBoxButton.YesNo;
case MessageButton.YesNoCancel: return MessageBoxButton.YesNoCancel;
default: return MessageBoxButton.OK;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static MessageButton ToMessageButton(this MessageBoxButton button)
{
switch (button)
{
case MessageBoxButton.OKCancel: return MessageButton.OKCancel;
case MessageBoxButton.YesNo: return MessageButton.YesNo;
case MessageBoxButton.YesNoCancel: return MessageButton.YesNoCancel;
default: return MessageButton.OK;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static MessageBoxImage ToMessageBoxImage(this MessageIcon icon)
{
switch (icon)
{
case MessageIcon.Error: return MessageBoxImage.Error;
case MessageIcon.Information: return MessageBoxImage.Information;
case MessageIcon.Question: return MessageBoxImage.Question;
case MessageIcon.Warning: return MessageBoxImage.Warning;
default: return MessageBoxImage.None;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static MessageIcon ToMessageIcon(this MessageBoxImage icon)
{
switch (icon)
{
case MessageBoxImage.Error: return MessageIcon.Error;
case MessageBoxImage.Information: return MessageIcon.Information;
case MessageBoxImage.Question: return MessageIcon.Question;
case MessageBoxImage.Warning: return MessageIcon.Warning;
default: return MessageIcon.None;
}
}
}
}
@@ -0,0 +1,124 @@
using MAX.Core.DependencyInjection;
using Store.Management.Framework.Configs;
using System.Windows;
using MessageBox = HandyControl.Controls.MessageBox;
namespace Store.Management.Framework
{
public class MessageBoxService : IMessageBoxService, ISingletonDependency
{
protected readonly Guid id = Guid.NewGuid();
public string MessageTitle { get; set; } = string.Empty;
public MessageBoxService()
{
MessageTitle = AppConfig.AppDisplayName;
}
public virtual MessageResult Show(string messageBoxText, string caption, MessageButton button, MessageIcon icon, MessageResult defaultResult)
{
Window? window = Application.Current?.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
if (window is null)
{
return MessageBox.Show(
messageBoxText: messageBoxText,
caption: caption,
button: button.ToMessageBoxButton(),
icon: icon.ToMessageBoxImage(),
defaultResult: defaultResult.ToMessageBoxResult()
).ToMessageResult();
}
else
{
return MessageBox.Show(
owner: window,
messageBoxText: messageBoxText,
caption: caption,
button: button.ToMessageBoxButton(),
icon: icon.ToMessageBoxImage(),
defaultResult: defaultResult.ToMessageBoxResult()
).ToMessageResult();
}
}
public void ShowInformation(string content)
{
this.ShowMessage(content, MessageTitle, MessageButton.OK, MessageIcon.Information, MessageResult.OK);
}
public void ShowWarning(string content)
{
this.ShowMessage(content, MessageTitle, MessageButton.OK, MessageIcon.Warning, MessageResult.OK);
}
public void ShowError(string content, Exception exception)
{
if (exception is null)
{
ShowError(content);
}
else
{
this.ShowMessage(content + "\n" + exception.Message, MessageTitle, MessageButton.OK, MessageIcon.Error, MessageResult.OK);
}
}
public void ShowError(string content)
{
this.ShowMessage(content, MessageTitle, MessageButton.OK, MessageIcon.Error, MessageResult.OK);
}
public bool ShowYesNoQuestion(string content)
{
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.YesNo, MessageIcon.Question, MessageResult.No);
return result == MessageResult.Yes;
}
public bool ShowYesNoWarning(string content)
{
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.YesNo, MessageIcon.Warning, MessageResult.No);
return result == MessageResult.Yes;
}
public bool ShowYesNoError(string content)
{
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.YesNo, MessageIcon.Error, MessageResult.No);
return result == MessageResult.Yes;
}
public bool ShowOkCancelQuestion(string content)
{
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.OKCancel, MessageIcon.Question, MessageResult.OK);
return result == MessageResult.OK;
}
public bool ShowOkCancelWarning(string content)
{
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.OKCancel, MessageIcon.Warning, MessageResult.OK);
return result == MessageResult.OK;
}
public bool ShowOkCancelError(string content)
{
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.OKCancel, MessageIcon.Error, MessageResult.OK);
return result == MessageResult.OK;
}
public MessageResult ShowYesNoCancelQuestion(string content)
{
return this.ShowMessage(content, MessageTitle, MessageButton.YesNoCancel, MessageIcon.Question, MessageResult.Cancel);
}
public MessageResult ShowYesNoCancelWarning(string content)
{
return this.ShowMessage(content, MessageTitle, MessageButton.YesNoCancel, MessageIcon.Warning, MessageResult.Cancel);
}
public MessageResult ShowYesNoCancelError(string content)
{
return this.ShowMessage(content, MessageTitle, MessageButton.YesNoCancel, MessageIcon.Error, MessageResult.Cancel);
}
}
}
@@ -0,0 +1,37 @@
namespace Store.Management.Framework
{
public static class MessageBoxServiceExtensions
{
extension(IMessageBoxService service)
{
public MessageResult ShowMessage(string messageBoxText, string caption, MessageButton button, MessageIcon icon, MessageResult defaultResult)
{
VerifyService(service);
return service.Show(messageBoxText, caption, button, icon, defaultResult);
}
public bool? ShowMessage(string messageBoxText)
{
return service.ShowMessage(messageBoxText, string.Empty);
}
public bool? ShowMessage(string messageBoxText, string caption)
{
return service.ShowMessage(messageBoxText, caption, MessageButton.OK).ToBool();
}
public MessageResult ShowMessage(string messageBoxText, string caption, MessageButton button)
{
return service.ShowMessage(messageBoxText, caption, button, MessageIcon.None);
}
public MessageResult ShowMessage(string messageBoxText, string caption, MessageButton button, MessageIcon icon)
{
VerifyService(service);
return service.Show(messageBoxText, caption, button, icon, MessageResult.None);
}
}
static void VerifyService(IMessageBoxService service)
{
if (service == null)
throw new ArgumentNullException(nameof(service));
}
}
}
@@ -0,0 +1,7 @@
namespace Store.Management.Framework
{
public enum MessageButton
{
OK, OKCancel, YesNoCancel, YesNo,
}
}
@@ -0,0 +1,8 @@
namespace Store.Management.Framework
{
public enum MessageIcon
{
None, Error, Question, Warning, Information,
Hand = Error, Stop = Error, Exclamation = Warning, Asterisk = Information
}
}
@@ -0,0 +1,7 @@
namespace Store.Management.Framework
{
public enum MessageResult
{
None, OK, Cancel, Yes, No,
}
}
@@ -0,0 +1,22 @@
using MAX.Core.DependencyInjection;
using Store.Management.Api;
using Store.Management.Api.Models;
using Store.Management.Api.Shops;
using Store.Management.Models;
namespace Store.Management.Framework.Services;
public interface IShopService
{
Task<IReadOnlyList<ShopCookieInfo>> GetCookiesAsync(string shopId, CancellationToken cancellationToken = default);
Task<PageResult<ShopInfo>> SearchAsync(ShopQueryRequest request, CancellationToken cancellationToken = default);
}
internal sealed class ShopService(StoreApiClient client) : IShopService, ISingletonDependency
{
public Task<IReadOnlyList<ShopCookieInfo>> GetCookiesAsync(string shopId, CancellationToken cancellationToken = default)
=> client.Shops.GetCookiesAsync(shopId, cancellationToken);
public Task<PageResult<ShopInfo>> SearchAsync(ShopQueryRequest request, CancellationToken cancellationToken = default)
=> client.Shops.SearchAsync(request, cancellationToken);
}
@@ -0,0 +1,44 @@
using MAX.Common.WPF.Helpers;
using MAX.Core.DependencyInjection;
using Prism.Mvvm;
namespace Store.Management.Framework.Services;
public enum StatusLevel
{
Info,
Success,
Warning,
Error
}
public sealed record StatusBarMessage(string Text, StatusLevel Level, int? Progress);
/// <summary>各页面共享主窗口底部的最新状态。</summary>
public interface IStatusBarService
{
StatusBarMessage Current { get; }
/// <summary>发布一条状态。进度范围为 0 到 100,省略时隐藏进度条。</summary>
void Report(string text, StatusLevel level = StatusLevel.Info, int? progress = null);
}
internal sealed class StatusBarService : BindableBase, IStatusBarService, ISingletonDependency
{
private StatusBarMessage _current = new("就绪", StatusLevel.Info, null);
public StatusBarMessage Current
{
get => _current;
private set => SetProperty(ref _current, value);
}
public void Report(string text, StatusLevel level = StatusLevel.Info, int? progress = null)
{
ArgumentNullException.ThrowIfNull(text);
if (progress is < 0 or > 100)
{
throw new ArgumentOutOfRangeException(nameof(progress), "进度必须在 0 到 100 之间。");
}
DispatcherHelper.RunInDispatcher(() => Current = new StatusBarMessage(text, level, progress));
}
}
@@ -0,0 +1,38 @@
using Store.Management.Models;
using MAX.Core.DependencyInjection;
using Store.Management.Api;
using Store.Management.Api.Users;
using Store.Management.Api.Models;
namespace Store.Management.Framework.Services;
public interface IUserService
{
Task<PageResult<UserInfo>> SearchAsync(UserSearchRequest request, CancellationToken cancellationToken = default);
Task<UserInfo> CreateAsync(UserCreateRequest request, CancellationToken cancellationToken = default);
Task<UserInfo> UpdateAsync(UserUpdateRequest request, CancellationToken cancellationToken = default);
Task<UserInfo> UpdateBillingAsync(UserBillingUpdateRequest request, CancellationToken cancellationToken = default);
Task ChangePasswordAsync(ChangePasswordRequest request, CancellationToken cancellationToken = default);
Task DeleteAsync(int id, CancellationToken cancellationToken = default);
}
internal sealed class UserService(StoreApiClient client) : IUserService, ISingletonDependency
{
public Task<PageResult<UserInfo>> SearchAsync(UserSearchRequest request, CancellationToken cancellationToken = default)
=> client.Users.SearchAsync(request, cancellationToken);
public Task<UserInfo> CreateAsync(UserCreateRequest request, CancellationToken cancellationToken = default)
=> client.Users.CreateAsync(request, cancellationToken);
public Task<UserInfo> UpdateAsync(UserUpdateRequest request, CancellationToken cancellationToken = default)
=> client.Users.UpdateAsync(request, cancellationToken);
public Task<UserInfo> UpdateBillingAsync(UserBillingUpdateRequest request, CancellationToken cancellationToken = default)
=> client.Users.UpdateBillingAsync(request, cancellationToken);
public Task ChangePasswordAsync(ChangePasswordRequest request, CancellationToken cancellationToken = default)
=> client.Users.ChangePasswordAsync(request, cancellationToken);
public Task DeleteAsync(int id, CancellationToken cancellationToken = default)
=> client.Users.DeleteAsync(id, cancellationToken);
}
@@ -0,0 +1,60 @@
using Autofac;
using MAX.Common.WPF.Converters;
using MAX.Common.WPF.Utilities;
using MAX.Core;
using MAX.Core.Autofac;
using MAX.Framework.Interfaces;
using Store.Management.Api;
using Store.Management.Framework.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Management.Framework
{
internal class Startup : IStartup
{
public int Priority => IntPriority.High;
public void Initialize()
{
EnumDisplayConverter.EnumDisplayManager = new EnumDisplayManagerWPF(null);
}
public void Register(ContainerBuilder builder)
{
var client = new StoreApiClient(new ApiClientOptions
{
BaseUrl = new Uri("http://localhost:14312/api/")
});
builder.Register(_ => client).SingleInstance().PreserveExistingDefaults();
DISource.Resolver = Resolve;
}
protected virtual object? Resolve(Type? type, string? name)
{
if (type == null)
{
return null;
}
if (IocManager.Container is not null)
{
if (name != null)
{
if (IocManager.Container.IsRegisteredWithName(name, type))
{
return IocManager.Container.ResolveNamed(name, type);
}
return null;
}
return IocManager.Resolve(type);
}
return Activator.CreateInstance(type);
}
}
}
@@ -10,8 +10,15 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Remove="Resources\Fonts\iconfont.ttf" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Store.Management.Models\Store.Management.Models.csproj" />
<PackageReference Include="Riok.Mapperly" Version="4.3.1" PrivateAssets="all" />
<PackageReference Include="HandyControl" Version="3.6.2.1" /> <PackageReference Include="HandyControl" Version="3.6.2.1" />
<PackageReference Include="MAX.Common.WPF" Version="1.4.23" /> <PackageReference Include="MAX.Common.WPF" Version="1.4.23" />
<ProjectReference Include="..\Store.Management.Api\Store.Management.Api.csproj" />
<ProjectReference Include="..\Core\MAX.Core\MAX.Core.csproj" /> <ProjectReference Include="..\Core\MAX.Core\MAX.Core.csproj" />
<ProjectReference Include="..\Core\MAX.Framework\MAX.Framework.csproj" /> <ProjectReference Include="..\Core\MAX.Framework\MAX.Framework.csproj" />
</ItemGroup> </ItemGroup>
@@ -21,4 +28,31 @@
<Folder Include="DependencyInjection\" /> <Folder Include="DependencyInjection\" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Resource Include="Resources\Fonts\iconfont.ttf" />
</ItemGroup>
<ItemGroup>
<None Update="Resources\Fonts\FontGeometry.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>FontGeometry.xaml</LastGenOutput>
</None>
<None Update="Resources\Fonts\IconEnum.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>IconEnum.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
<ItemGroup>
<Compile Update="Resources\Fonts\IconEnum.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>IconEnum.tt</DependentUpon>
</Compile>
</ItemGroup>
</Project> </Project>
@@ -1,5 +0,0 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Store.Management.Framework;component/Controls/DataGridEx/DataGridEx.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
@@ -0,0 +1,14 @@
namespace Store.Management.Framework.ViewModels;
public sealed class ShopItemViewModel
{
public int Id { get; init; }
public string? UserName { get; init; }
public string? ShopId { get; init; }
public string? ShopAccount { get; init; }
public string? LoginStatus { get; init; }
public bool IsLoggedOut => LoginStatus?.Contains("未登录", StringComparison.Ordinal) == true;
public string? CompanyName { get; init; }
public string? Notes { get; init; }
public string? GroupName { get; init; }
}
@@ -0,0 +1,26 @@
using Store.Management.Models;
namespace Store.Management.Framework.ViewModels;
public sealed class UserItemViewModel
{
public int Id { get; init; }
public string UserName { get; init; } = "";
public string? NickName { get; init; }
public string? Mobile { get; init; }
public string? CompanyName { get; init; }
public string? Notes { get; init; }
public string? ParentUserName { get; init; }
public int GroupId { get; init; }
public UserGroup? Group => GroupId is >= byte.MinValue and <= byte.MaxValue ? (UserGroup)GroupId : null;
public UserAdminLevel? SaLevel { get; init; }
public string? OemId { get; init; }
public string? Authority { get; init; }
public int ShopPointsPerMonth { get; init; }
public decimal? PostagePerOrder { get; init; }
public decimal? RefundPostagePerOrder { get; init; }
public decimal? GiftOemAmountPerOrder { get; init; }
public decimal? SyncLogisticsPerOrder { get; init; }
public decimal Points { get; init; }
public decimal? Balance { get; init; }
}
@@ -0,0 +1,3 @@
namespace Store.Management.Models;
public sealed record CurrentUser(string UserName, string? NickName);
@@ -0,0 +1,8 @@
namespace Store.Management.Models;
public sealed class LoginResult
{
public string TokenType { get; init; } = "Bearer";
public string Token { get; init; } = "";
public uint ExpiresInMinutes { get; init; }
}
@@ -0,0 +1,7 @@
namespace Store.Management.Models;
public sealed class ShopCookieInfo
{
public required string ShopId { get; init; }
public required string Cookies { get; init; }
}
@@ -0,0 +1,14 @@
namespace Store.Management.Models;
/// <summary>商铺列表所需的服务端字段。</summary>
public sealed class ShopInfo
{
public int Id { get; init; }
public string? UserName { get; init; }
public string? ShopId { get; init; }
public string? ShopAccount { get; init; }
public string? LoginStatus { get; init; }
public string? CompanyName { get; init; }
public string? Notes { get; init; }
public string? GroupName { get; init; }
}
@@ -0,0 +1,3 @@
<Project Sdk="Microsoft.NET.Sdk">
</Project>
@@ -0,0 +1,7 @@
namespace Store.Management.Models;
public enum UserAdminLevel : short
{
[System.ComponentModel.Description("普通用户")] Normal = 0,
[System.ComponentModel.Description("超级管理员")] SuperAdmin = 1
}
@@ -0,0 +1,9 @@
namespace Store.Management.Models;
public enum UserGroup : byte
{
/// <summary>主号。</summary>
[System.ComponentModel.Description("主号")] MainAccount = 3,
/// <summary>客服。</summary>
[System.ComponentModel.Description("客服")] CustomerService = 4,
}
@@ -0,0 +1,24 @@
namespace Store.Management.Models;
/// <summary>管理端当前使用的用户资料字段;不接收密码。</summary>
public sealed class UserInfo
{
public int Id { get; init; }
public string UserName { get; init; } = "";
public string? NickName { get; init; }
public string? Mobile { get; init; }
public string? CompanyName { get; init; }
public string? Notes { get; init; }
public string? ParentUserName { get; init; }
public int GroupId { get; init; }
public UserAdminLevel? SaLevel { get; init; }
public string? OemId { get; init; }
public string? Authority { get; init; }
public int ShopPointsPerMonth { get; init; }
public decimal? PostagePerOrder { get; init; }
public decimal? RefundPostagePerOrder { get; init; }
public decimal? GiftOemAmountPerOrder { get; init; }
public decimal? SyncLogisticsPerOrder { get; init; }
public decimal Points { get; init; }
public decimal? Balance { get; init; }
}
+3 -7
View File
@@ -5,16 +5,12 @@
xmlns:mf="clr-namespace:Store.Management.Framework;assembly=Store.Management.Framework"> xmlns:mf="clr-namespace:Store.Management.Framework;assembly=Store.Management.Framework">
<Application.Resources> <Application.Resources>
<ResourceDictionary> <ResourceDictionary>
<SolidColorBrush x:Key="PrimaryBrush" Color="#3267C8" />
<SolidColorBrush x:Key="TextIconBrush" Color="#FFFFFF" />
<SolidColorBrush x:Key="BackgroundBrush" Color="#FFFFFF" />
<Style x:Key="DialogWindowStyle" TargetType="Window">
<Setter Property="ResizeMode" Value="NoResize" />
</Style>
<ResourceDictionary.MergedDictionaries> <ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Store.Management.Framework;component/Resources/HandyControlBasic.xaml" /> <ResourceDictionary Source="pack://application:,,,/Store.Management.Framework;component/Resources/HandyControlBasic.xaml" />
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml" /> <ResourceDictionary Source="/Store.Management.Framework;component/Resources/Colors.xaml" />
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml" /> <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml" />
<ResourceDictionary Source="pack://application:,,,/Store.Management.Framework;component/Resources/FrameworkTheme.xaml" /> <ResourceDictionary Source="pack://application:,,,/Store.Management.Framework;component/Resources/FrameworkTheme.xaml" />
+55 -39
View File
@@ -2,28 +2,19 @@ using MAX.Notification;
using Prism.Ioc; using Prism.Ioc;
using Prism.Mvvm; using Prism.Mvvm;
using Prism.Services.Dialogs; using Prism.Services.Dialogs;
using Store.Management.Api;
using Store.Management.Framework; using Store.Management.Framework;
using Store.Management.Notifications; using Store.Management.Notifications;
using Store.Management.Services; using Store.Management.Services;
using Store.Management.ViewModels; using Store.Management.ViewModels;
using Store.Management.Views; using Store.Management.Views;
using Store.Management.Views.Dialogs;
using System.Diagnostics;
using System.Windows; using System.Windows;
namespace Store.Management; namespace Store.Management;
public partial class App : FrameworkApplication public partial class App : FrameworkApplication
{ {
private readonly StoreApiClient? _apiClient; private AppSplashScreen _appSplashScreen;
protected override Window CreateShell()
public App() { }
public App(StoreApiClient apiClient) => _apiClient = apiClient ?? throw new ArgumentNullException(nameof(apiClient));
private StoreApiClient CreateApiClient() => _apiClient ?? new(new ApiClientOptions
{
BaseUrl = new Uri("http://localhost:14312/api/")
});
protected override Window CreateShell()
{ {
if (Environment.GetCommandLineArgs().Contains("--grid-demo")) if (Environment.GetCommandLineArgs().Contains("--grid-demo"))
{ {
@@ -37,10 +28,33 @@ public partial class App : FrameworkApplication
} }
return Container.Resolve<MainWindow>(); return Container.Resolve<MainWindow>();
} }
protected override void OnStartup(StartupEventArgs e)
{
_appSplashScreen = new()
{
CloseCallBack = () =>
{
base.OnStartup(e);
},
};
_appSplashScreen.ShowDialog();
}
protected override async void OnInitialized()
{
try
{
//await LoadModules();
base.OnInitialized();
_appSplashScreen.Close();
_appSplashScreen = null;
}
catch (Exception ex)
{
Fatal(ex);
Debug.WriteLine(ex);
}
protected override void OnInitialized()
{
base.OnInitialized();
//base.OnInitialized(); //base.OnInitialized();
//// 登录弹窗关闭与主窗口创建之间不触发 WPF 的最后窗口退出。 //// 登录弹窗关闭与主窗口创建之间不触发 WPF 的最后窗口退出。
//ShutdownMode = ShutdownMode.OnExplicitShutdown; //ShutdownMode = ShutdownMode.OnExplicitShutdown;
@@ -63,32 +77,34 @@ public partial class App : FrameworkApplication
{ {
containerRegistry.RegisterDialogWindow<Framework.Controls.DialogWindow>(); containerRegistry.RegisterDialogWindow<Framework.Controls.DialogWindow>();
containerRegistry.RegisterDialog<UserBillingDialog, UserBillingDialogViewModel>();
containerRegistry.RegisterDialog<UserEditorDialog, UserEditorDialogViewModel>();
containerRegistry.RegisterDialog<DataGridTestView, DataGridTestViewModel>(); containerRegistry.RegisterDialog<DataGridTestView, DataGridTestViewModel>();
ViewModelLocationProvider.Register<MainWindow, MainWindowViewModel>(); ViewModelLocationProvider.Register<MainWindow, MainViewModel>();
containerRegistry.RegisterDialog<LoginWindow, LoginViewModel>();
//registry.RegisterInstance(CreateApiClient()); containerRegistry.RegisterForNavigation<UserManagementPage, UserManagementPageViewModel>(nameof(UserManagementPage));
// registry.Register<LoginViewModel>(provider => new LoginViewModel(provider.Resolve<StoreApiClient>().Auth)); containerRegistry.RegisterForNavigation<ShopManagementView, ShopManagementViewModel>(nameof(ShopManagementView));
// registry.RegisterSingleton<SingletonProbe>(); containerRegistry.RegisterForNavigation<DataGridTestView, DataGridTestViewModel>(nameof(DataGridTestView));
// registry.Register<TransientProbe>();
// registry.RegisterSingleton<NotificationExampleState>();
// registry.Register<IPublisher>(provider => new NotificationPublisher( // registry.RegisterSingleton<SingletonProbe>();
// new PrismNotificationServiceProvider(provider))); // registry.Register<TransientProbe>();
// // 显式提供处理器集合,展示一条通知分发给多个业务模块。 // registry.RegisterSingleton<NotificationExampleState>();
// registry.Register<IEnumerable<INotificationHandler<ProductSavedNotification>>>(provider => // registry.Register<IPublisher>(provider => new NotificationPublisher(
// new INotificationHandler<ProductSavedNotification>[] // new PrismNotificationServiceProvider(provider)));
// { // // 显式提供处理器集合,展示一条通知分发给多个业务模块。
// new ProductCacheHandler(provider.Resolve<NotificationExampleState>()), // registry.Register<IEnumerable<INotificationHandler<ProductSavedNotification>>>(provider =>
// new ProductAuditHandler(provider.Resolve<NotificationExampleState>()) // new INotificationHandler<ProductSavedNotification>[]
// }); // {
// registry.RegisterDialog<LoginWindow, LoginViewModel>(); // new ProductCacheHandler(provider.Resolve<NotificationExampleState>()),
// registry.RegisterDialog<FrameworkTestDialog, FrameworkTestDialogViewModel>(); // new ProductAuditHandler(provider.Resolve<NotificationExampleState>())
} // });
// registry.RegisterDialog<LoginWindow, LoginViewModel>();
// registry.RegisterDialog<FrameworkTestDialog, FrameworkTestDialogViewModel>();
}
protected override void OnExit(ExitEventArgs e)
{
//try { Container?.Resolve<StoreApiClient>().Dispose(); }
//finally { base.OnExit(e); }
}
} }
-20
View File
@@ -1,20 +0,0 @@
<f:WindowBase
x:Class="Store.Management.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:f="Store.Management.Framework"
xmlns:views="clr-namespace:Store.Management.Views"
Title="{Binding Title}"
Width="960"
Height="720"
MinWidth="720"
MinHeight="560"
WindowStartupLocation="CenterScreen">
<DockPanel>
<!-- 控件测试入口 -->
<Button DockPanel.Dock="Top" Content="打开 DataGrid 测试"
Command="{Binding OpenDataGridTestCommand, Mode=OneWay}"
HorizontalAlignment="Left" Margin="16,12" Padding="16,6" />
<views:FrameworkTestPage />
</DockPanel>
</f:WindowBase>
@@ -1,25 +0,0 @@
using Prism.Mvvm;
using Prism.Commands;
using Prism.Services.Dialogs;
using Store.Management.Views;
using Store.Management.Framework.Controls;
using System.Windows;
namespace Store.Management;
public partial class MainWindow : WindowBase
{
public MainWindow() => InitializeComponent();
}
public class MainWindowViewModel(IDialogService dialogService) : BindableBase
{
public DelegateCommand OpenDataGridTestCommand => field ??= new(() =>
dialogService.ShowDialog(nameof(DataGridTestView), new DialogParameters(), _ => { }));
private string _title="TTTT";
public string Title
{
get => _title;
set => SetProperty(ref _title, value);
}
}
@@ -1,5 +1,4 @@
using Bogus; using Bogus;
using ConfirmDialogViewModel = MAX.Framework.Controls.ConfirmDialogViewModel;
using Prism.Commands; using Prism.Commands;
using Prism.Mvvm; using Prism.Mvvm;
using Store.Management.Framework.Controls; using Store.Management.Framework.Controls;
@@ -1,5 +1,5 @@
using MAX.Framework.Controls;
using Prism.Services.Dialogs; using Prism.Services.Dialogs;
using Store.Management.Framework.Controls;
namespace Store.Management.ViewModels; namespace Store.Management.ViewModels;
public sealed class FrameworkTestDialogViewModel : ConfirmDialogViewModel public sealed class FrameworkTestDialogViewModel : ConfirmDialogViewModel
{ {
@@ -2,12 +2,12 @@ using Prism.Commands;
using MAX.Notification; using MAX.Notification;
using Store.Management.Notifications; using Store.Management.Notifications;
using Prism.Ioc; using Prism.Ioc;
using Prism.Mvvm; using Store.Management.Framework.Controls;
using Prism.Services.Dialogs; using Prism.Services.Dialogs;
using Store.Management.Services; using Store.Management.Services;
using Store.Management.Views; using Store.Management.Views;
namespace Store.Management.ViewModels; namespace Store.Management.ViewModels;
public sealed class FrameworkTestPageViewModel : BindableBase public sealed class FrameworkTestPageViewModel : ViewModelBase
{ {
private readonly IContainerProvider container; private readonly IContainerProvider container;
private readonly SingletonProbe singleton; private readonly SingletonProbe singleton;
@@ -1,19 +1,33 @@
using System.Security.Cryptography; using Prism.Commands;
using System.Text;
using Prism.Commands;
using MAX.Framework.Controls;
using Prism.Services.Dialogs; using Prism.Services.Dialogs;
using System.Windows.Input;
using Store.Management.Api.Authentication;
using Store.Management.Api.Transport; using Store.Management.Api.Transport;
using Store.Management.Framework.Controls;
using Store.Management.Framework.Services;
using Store.Management.Framework.ViewModels; using Store.Management.Framework.ViewModels;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Input;
namespace Store.Management.ViewModels; namespace Store.Management.ViewModels;
/// <summary>登录校验、认证请求和窗口生命周期内的请求取消。</summary> public enum EEE
public sealed class LoginViewModel(IAuthApi auth) : ConfirmDialogViewModel, IDisposable
{ {
private readonly IAuthApi _auth = auth ?? throw new ArgumentNullException(nameof(auth)); [Description("管理员")]
Admin,
[Description("用户")]
User
}
/// <summary>登录校验、认证请求和窗口生命周期内的请求取消。</summary>
public sealed class LoginViewModel(ILoginService loginService) : ConfirmDialogViewModel, IDisposable
{
private EEE _ee;
public EEE ee
{
get => _ee;
set => SetProperty(ref _ee, value);
}
private readonly CancellationTokenSource _lifetime = new(); private readonly CancellationTokenSource _lifetime = new();
private string _userName = ""; private string _userName = "";
private string _passwordHash = ""; private string _passwordHash = "";
@@ -38,9 +52,11 @@ public sealed class LoginViewModel(IAuthApi auth) : ConfirmDialogViewModel, IDis
// 服务端要求 UTF-8 密码的 32 位大写 MD5,保留首尾空格。 // 服务端要求 UTF-8 密码的 32 位大写 MD5,保留首尾空格。
_passwordHash = string.IsNullOrEmpty(password) _passwordHash = string.IsNullOrEmpty(password)
? "" : Convert.ToHexString(MD5.HashData(Encoding.UTF8.GetBytes(password))); ? "" : HashPassword(password);
} }
internal static string HashPassword(string password) => Convert.ToHexString(MD5.HashData(Encoding.UTF8.GetBytes(password)));
public override ICommand ConfirmCommand => LoginCommand; public override ICommand ConfirmCommand => LoginCommand;
public override void OnDialogOpened(IDialogParameters parameters) public override void OnDialogOpened(IDialogParameters parameters)
@@ -73,11 +89,7 @@ public sealed class LoginViewModel(IAuthApi auth) : ConfirmDialogViewModel, IDis
NotifyStateChanged(); NotifyStateChanged();
try try
{ {
await _auth.LoginAsync(new LoginRequest await loginService.LoginAsync(UserName, _passwordHash, _lifetime.Token);
{
UserName = UserName.Trim(),
Password = _passwordHash
}, _lifetime.Token);
if (!_disposed) if (!_disposed)
{ {
_authenticated = true; _authenticated = true;
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Management.ViewModels
{
partial class MainViewModel
{
partial void InitHeader()
{
}
}
}
@@ -0,0 +1,50 @@
using MAX.Common.Helpers;
using PipeReviewReport.Resources.Fonts;
using Prism.Commands;
using Prism.Regions;
using Store.Management.Framework;
using Store.Management.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Store.Management.ViewModels
{
partial class MainViewModel
{
public ObservableCollection<NavItemViewModel> NavItems { get; } = [];
partial void InitNav()
{
NavItems.Add(new NavItemViewModel
{
Code = "1",
Title = "角色管理",
Icon = IconNameEnum.Person,
Url = nameof(UserManagementPage)
});
NavItems.Add(new NavItemViewModel
{
Code = "1",
Title = "商铺管理",
Icon = IconNameEnum.BuildingShop,
Url = nameof(ShopManagementView),
IsSelected = true,
});
}
public ICommand NavItemCommand => new AsyncDelegateCommand<NavItemViewModel>(NavItem);
private async Task NavItem(NavItemViewModel model)
{
NavItems.ForEach(a => a.IsSelected = false);
model.IsSelected = true;
_regionManager.RequestNavigate(Navigation.MainContext, model.Url);
}
}
}
@@ -0,0 +1,26 @@
using Store.Management.Framework.Services;
using Store.Management.Framework.Controls;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Management.ViewModels
{
partial class MainViewModel : ViewModelBase
{
private readonly IRegionManager _regionManager;
public IStatusBarService StatusBar { get; }
public MainViewModel(IRegionManager regionManager, IStatusBarService statusBar)
{
_regionManager = regionManager;
StatusBar = statusBar;
InitNav();
InitHeader();
}
partial void InitNav();
partial void InitHeader();
}
}
@@ -0,0 +1,19 @@
using PipeReviewReport.Resources.Fonts;
using Prism.Mvvm;
namespace Store.Management.ViewModels
{
public class NavItemViewModel : BindableBase
{
public string Code { get; set; }
public string Title { get; set; }
public IconNameEnum Icon { get; set; }
public string Url { get; set; }
private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set => SetProperty(ref _isSelected, value);
}
}
}
@@ -0,0 +1,117 @@
using Prism.Commands;
using Store.Management.Api.Models;
using Store.Management.Api.Shops;
using Store.Management.Api.Transport;
using Store.Management.Framework.Controls;
using Store.Management.Framework.Mappers;
using Store.Management.Framework.Services;
using Store.Management.Framework.ViewModels;
using Store.Management.Models;
namespace Store.Management.ViewModels;
public sealed class ShopManagementViewModel(IShopService shopService, IStatusBarService statusBar) : ViewModelBase
{
public const int SearchTextLimit = 250;
private string account = string.Empty;
private string shopId = string.Empty;
private string shopName = string.Empty;
private string notes = string.Empty;
private int page = 1;
private int pageSize = 50;
private int total;
private IReadOnlyList<ShopItemViewModel> shops = [];
private ShopQueryRequest appliedQuery = new();
public string Account { get => account; set => SetProperty(ref account, value); }
public string ShopId { get => shopId; set => SetProperty(ref shopId, value); }
public string ShopName { get => shopName; set => SetProperty(ref shopName, value); }
public string Notes { get => notes; set => SetProperty(ref notes, value); }
public int Page { get => page; private set => SetProperty(ref page, value); }
public int Total { get => total; private set => SetProperty(ref total, value); }
public IReadOnlyList<ShopItemViewModel> Shops { get => shops; private set => SetProperty(ref shops, value); }
public LoadingStatus LoadingStatus { get; } = new();
public AsyncDelegateCommand SearchCommand => field ??= new(SearchAsync);
private Task SearchAsync() => LoadAsync(new ShopQueryRequest
{
SearchUserName = Account.Trim(), SearchId = ShopId.Trim(),
SearchName = ShopName.Trim(), SearchNotes = Notes.Trim(), PageSize = pageSize
});
public AsyncDelegateCommand ResetCommand => field ??= new(ResetAsync);
private Task ResetAsync()
{
Account = ShopId = ShopName = Notes = string.Empty;
return SearchAsync();
}
public AsyncDelegateCommand<DataGridPageRequest> PageCommand => field ??= new(request => LoadAsync(new ShopQueryRequest
{
SearchUserName = appliedQuery.SearchUserName, SearchId = appliedQuery.SearchId,
SearchName = appliedQuery.SearchName, SearchNotes = appliedQuery.SearchNotes,
Page = request.PageIndex, PageSize = request.PageSize
}));
public AsyncDelegateCommand<ShopItemViewModel> CopyCookieCommand => field ??= new(CopyCookieAsync,
shop => !string.IsNullOrWhiteSpace(shop?.ShopId));
private async Task CopyCookieAsync(ShopItemViewModel shop)
{
try
{
IReadOnlyList<ShopCookieInfo> cookies = await shopService.GetCookiesAsync(shop.ShopId!);
string? cookie = cookies.FirstOrDefault(item => item.ShopId == shop.ShopId)?.Cookies;
if (string.IsNullOrWhiteSpace(cookie))
{
statusBar.Report("该店铺没有可复制的 Cookie。", StatusLevel.Warning);
return;
}
System.Windows.Clipboard.SetText(cookie);
statusBar.Report("Cookie 已复制。", StatusLevel.Success);
}
catch (ApiException ex)
{
statusBar.Report(ex.Message, StatusLevel.Error);
}
catch (System.Runtime.InteropServices.COMException)
{
statusBar.Report("剪贴板暂时不可用,请重试。", StatusLevel.Error);
}
}
protected override void OnLoadedOnce() => _ = SearchAsync();
private async Task LoadAsync(ShopQueryRequest request)
{
if (LoadingStatus.IsLoading)
{
return;
}
LoadingStatus.Initialize("正在查询商铺…");
try
{
PageResult<ShopInfo> result = await shopService.SearchAsync(request);
int lastPage = (int)Math.Clamp((result.Total - 1) / request.PageSize + 1, 1, request.Page);
if (request.Page > lastPage)
{
request.Page = lastPage;
result = await shopService.SearchAsync(request);
}
appliedQuery = request;
pageSize = request.PageSize;
Shops = ShopMapper.ToItemViewModels(result.Items);
Total = (int)Math.Min(result.Total, int.MaxValue);
Page = request.Page;
LoadingStatus.Done();
statusBar.Report($"商铺查询完成,共 {Total} 条。", StatusLevel.Success, 100);
}
catch (ApiException ex)
{
Shops = [];
Total = 0;
Page = 1;
LoadingStatus.Error(ex.Message);
statusBar.Report(ex.Message, StatusLevel.Error);
}
}
}
@@ -0,0 +1,185 @@
using Store.Management.Framework.Mappers;
using Store.Management.Framework.ViewModels;
using Store.Management.Models;
using Prism.Commands;
using Prism.Services.Dialogs;
using Store.Management.Api.Transport;
using Store.Management.Api.Users;
using Store.Management.Framework.Controls;
using Store.Management.Framework.Services;
using System.ComponentModel.DataAnnotations;
using System.Windows.Input;
namespace Store.Management.ViewModels;
public sealed class UserEditorDialogViewModel(IUserService userService) : ConfirmDialogViewModel
{
public const int UserNameLimit = 20;
public const int PasswordLimit = 128;
public const int NickNameLimit = 50;
public const int MobileLimit = 30;
public const int CompanyLimit = 100;
public const int NotesLimit = 255;
public const int AgentCodeLimit = 50;
public sealed class PermissionOption(string name)
{
public string Name { get; } = name;
public bool IsSelected { get; set; }
}
public PermissionOption[] Permissions { get; } =
[
new("微信回采"), new("货源选择"), new("评分考核"), new("爆款数据"),
new("在线寄件"), new("佣金上货"), new("充值用户"), new("商品采集"),
new("裂变调试"), new("学员数据"), new("定向品牌"), new("活动库存")
];
private UserItemViewModel? user;
private string? passwordHash;
private string? confirmationHash;
private string? oldPasswordHash;
public bool ShowOldPassword => !IsCreate && passwordHash != null;
public string? ParentUserName { get; set; }
public bool IsCreatingSubUser => IsCreate && Group != UserGroup.MainAccount;
public UserGroup? Group
{
get;
set
{
if (SetProperty(ref field, value))
{
RaisePropertyChanged(nameof(IsCreatingSubUser));
}
}
}
public UserAdminLevel Level { get; set => SetProperty(ref field, value); }
public string AgentCode { get; set => SetProperty(ref field, value); } = "";
public bool IsCreate => user == null;
public string UserName { get; set => SetProperty(ref field, value); } = "";
public UserEditRequest Draft { get; private set => SetProperty(ref field, value); } = new();
public override void OnDialogOpened(IDialogParameters parameters)
{
user = parameters.GetValue<UserItemViewModel?>("user");
UserName = user?.UserName ?? "";
Draft = user == null ? new UserCreateRequest() : new UserUpdateRequest
{
Id = user.Id, NickName = user.NickName, Mobile = user.Mobile,
CompanyName = user.CompanyName, Notes = user.Notes
};
Group = user == null ? UserGroup.MainAccount : (UserGroup)user.GroupId;
Level = user?.SaLevel ?? UserAdminLevel.Normal;
AgentCode = user?.OemId ?? "";
var granted = (user?.Authority ?? "").Split(',', StringSplitOptions.TrimEntries);
foreach (var option in Permissions)
{
option.IsSelected = granted.Contains(option.Name);
}
Title = IsCreate ? "创建用户" : "编辑用户";
RaisePropertyChanged(nameof(IsCreate));
}
public void UpdatePasswords(string password, string confirmation, string oldPassword)
{
passwordHash = password.Length == 0 ? null : password.Length >= 6 && !string.IsNullOrWhiteSpace(password)
? LoginViewModel.HashPassword(password) : "";
oldPasswordHash = oldPassword.Length == 0 ? null : LoginViewModel.HashPassword(oldPassword);
RaisePropertyChanged(nameof(ShowOldPassword));
confirmationHash = confirmation.Length == 0 ? null : LoginViewModel.HashPassword(confirmation);
}
public override bool CanCloseDialog() => !IsLoading;
public override ICommand ConfirmCommand => field ??= new AsyncDelegateCommand(SaveAsync);
private async Task SaveAsync()
{
if (string.IsNullOrWhiteSpace(Draft.NickName) || string.IsNullOrWhiteSpace(Draft.Mobile))
{
ErrorMsg = "请输入昵称和手机号。";
return;
}
if (Draft.Mobile.Trim().Length != 11 || !Draft.Mobile.Trim().All(char.IsAsciiDigit))
{
ErrorMsg = "手机号应为 11 位数字。";
return;
}
if (passwordHash == "" || (IsCreate && passwordHash == null))
{
ErrorMsg = "请输入至少 6 位密码。";
return;
}
if (passwordHash != confirmationHash)
{
ErrorMsg = "两次输入的密码不一致。";
return;
}
if (Group == null || (user != null && Group != (UserGroup)user.GroupId &&
(Group == UserGroup.MainAccount || user.GroupId == (int)UserGroup.MainAccount)))
{
ErrorMsg = "请选择有效分组,已有账户不能切换主号和子账号。";
return;
}
Draft.GroupId = user?.GroupId == (int?)Group ? null : Group;
Draft.SaLevel = Level == (user?.SaLevel ?? UserAdminLevel.Normal) ? null : Level;
Draft.OemId = AgentCode.Trim() == (user?.OemId ?? "") ? null : AgentCode.Trim();
var granted = (user?.Authority ?? "").Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).ToHashSet();
bool changed = false;
foreach (var option in Permissions)
{
changed |= option.IsSelected ? granted.Add(option.Name) : granted.Remove(option.Name);
}
Draft.Authority = changed ? string.Join(",", granted) : null;
if (Draft is UserCreateRequest create)
{
create.ParentUserName = IsCreatingSubUser ? ParentUserName : null;
create.UserName = Draft.Mobile.Trim();
create.Password = passwordHash!;
}
IsLoading = true;
ErrorMsg = "";
bool profileSaved = false;
try
{
if (Draft is UserCreateRequest newUser)
{
await userService.CreateAsync(newUser);
}
else
{
user = UserMapper.ToItemViewModel(await userService.UpdateAsync((UserUpdateRequest)Draft));
profileSaved = true;
if (passwordHash != null)
{
await userService.ChangePasswordAsync(new ChangePasswordRequest(UserName, passwordHash, oldPasswordHash));
}
}
}
catch (ApiException ex)
{
ErrorMsg = profileSaved ? $"资料已保存,密码修改失败:{ex.Message}" : ex.Message;
return;
}
catch (ValidationException ex)
{
ErrorMsg = ex.Message;
return;
}
finally
{
IsLoading = false;
}
OnRequestClose(new DialogResult(ButtonResult.OK));
}
public override void OnDialogClosed()
{
passwordHash = confirmationHash = oldPasswordHash = null;
if (Draft is UserCreateRequest create)
{
create.Password = "";
}
}
}
@@ -0,0 +1,142 @@
using Store.Management.Framework.Mappers;
using Store.Management.Framework.ViewModels;
using Store.Management.Models;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using Store.Management.Api.Transport;
using Store.Management.Api.Users;
using Store.Management.Framework.Controls;
using Store.Management.Framework.Services;
using Store.Management.Views;
using Store.Management.Views.Dialogs;
using System.Windows;
using System.Windows.Controls.Primitives;
using Store.Management.Api.Models;
namespace Store.Management.ViewModels;
public sealed class UserManagementPageViewModel(IUserService userService, IDialogService dialogs, IStatusBarService statusBar) : ViewModelBase
{
public const int KeywordLimit = 100;
private string appliedKeyword = "";
private UserGroup? appliedGroup;
private int pageSize = 50;
public string Keyword { get; set; } = "";
public UserGroup? SelectedGroup { get; set; }
private bool _canInteract = true;
public bool CanInteract { get => _canInteract; private set => SetProperty(ref _canInteract, value); }
public int Page { get; private set => SetProperty(ref field, value); } = 1;
public int Total { get; private set => SetProperty(ref field, value); }
public IReadOnlyList<UserItemViewModel> Users { get; private set => SetProperty(ref field, value); } = [];
public UserItemViewModel? SelectedUser { get; set => SetProperty(ref field, value); }
public AsyncDelegateCommand SearchCommand => field ??= new(() => LoadAsync(Keyword.Trim(), SelectedGroup, 1, pageSize));
public AsyncDelegateCommand<DataGridPageRequest> PageCommand => field ??= new(
request => LoadAsync(appliedKeyword, appliedGroup, request.PageIndex, request.PageSize), _ => CanInteract);
public AsyncDelegateCommand CreateCommand => field ??= new(() => OpenEditorAsync(null));
public AsyncDelegateCommand EditCommand => field ??= new AsyncDelegateCommand(() => OpenEditorAsync(SelectedUser),
() => SelectedUser != null).ObservesProperty(() => SelectedUser);
public AsyncDelegateCommand BillingCommand => field ??= new AsyncDelegateCommand(async () =>
{
ButtonResult result = ButtonResult.None;
dialogs.ShowDialog(nameof(UserBillingDialog), SelectedUser!, response => result = response.Result);
if (result == ButtonResult.OK)
{
await LoadAsync(appliedKeyword, appliedGroup, Page, pageSize);
}
}, () => SelectedUser != null).ObservesProperty(() => SelectedUser);
public AsyncDelegateCommand DeleteCommand => field ??= new AsyncDelegateCommand(DeleteAsync,
() => SelectedUser != null).ObservesProperty(() => SelectedUser);
protected override void OnLoadedOnce()
{
_ = LoadAsync(Keyword.Trim(), SelectedGroup, 1, pageSize);
}
private async Task LoadAsync(string keyword, UserGroup? group, int page, int size)
{
if (!CanInteract)
{
return;
}
CanInteract = false;
try
{
statusBar.Report("正在查询用户…");
UserSearchRequest request = new() { Keyword = keyword, GroupId = (int?)group, Page = page, PageSize = size };
PageResult<UserInfo> result = await userService.SearchAsync(request);
// 删除末页最后一条记录后,按服务端总数回到有效页。
int lastPage = (int)Math.Clamp((result.Total - 1) / size + 1, 1, page);
if (page > lastPage)
{
request.Page = lastPage;
result = await userService.SearchAsync(request);
}
appliedKeyword = keyword;
appliedGroup = group;
pageSize = size;
SelectedUser = null;
Users = UserMapper.ToItemViewModels(result.Items);
Total = (int)Math.Min(result.Total, int.MaxValue);
Page = request.Page;
statusBar.Report($"用户查询完成,共 {Total} 条。", StatusLevel.Success, 100);
}
catch (ApiException ex)
{
SelectedUser = null;
Users = [];
Total = 0;
Page = 1;
appliedKeyword = keyword;
appliedGroup = group;
pageSize = size;
statusBar.Report(ex.Message, StatusLevel.Error);
}
finally
{
CanInteract = true;
}
}
private async Task OpenEditorAsync(UserItemViewModel? user)
{
ButtonResult result = ButtonResult.None;
dialogs.ShowDialog(nameof(UserEditorDialog), new DialogParameters { { "user", user } },
response => result = response.Result);
if (result == ButtonResult.OK)
{
await LoadAsync(appliedKeyword, appliedGroup, user == null ? 1 : Page, pageSize);
}
}
private async Task DeleteAsync()
{
UserItemViewModel user = SelectedUser!;
if (MessageBox.Show($"确定删除用户“{user.UserName}”?", "删除用户", MessageBoxButton.OKCancel,
MessageBoxImage.Warning, MessageBoxResult.Cancel) != MessageBoxResult.OK)
{
return;
}
CanInteract = false;
try
{
statusBar.Report("正在删除用户…");
await userService.DeleteAsync(user.Id);
}
catch (ApiException ex)
{
statusBar.Report(ex.Message, StatusLevel.Error);
return;
}
finally
{
CanInteract = true;
}
await LoadAsync(appliedKeyword, appliedGroup, Page, pageSize);
}
}
@@ -0,0 +1,24 @@
<Window
x:Class="Store.Management.Views.AppSplashScreen"
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:local="clr-namespace:Store.Management.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="AppSplashScreen"
Width="990"
Height="570"
AllowsTransparency="True"
Background="Transparent"
ResizeMode="NoResize"
ShowInTaskbar="False"
Topmost="True"
WindowStartupLocation="CenterScreen"
WindowStyle="None"
mc:Ignorable="d">
<Border>
<!--<Viewbox>
<TextBlock Foreground="#dedede" Text="启动" />
</Viewbox>-->
</Border>
</Window>
@@ -0,0 +1,136 @@
using Store.Management.Framework.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Shapes;
namespace Store.Management.Views
{
/// <summary>
/// AppSplashScreen.xaml 的交互逻辑
/// </summary>
public partial class AppSplashScreen : Window
{
public Action CloseCallBack { get; set; }
public AppSplashScreen()
{
InitializeComponent();
Loaded += StartView_Loaded;
Unloaded += StartView_Unloaded;
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
Activate();
}
private void StartView_Loaded(object sender, RoutedEventArgs e)
{
Activate();
}
private void StartView_Unloaded(object sender, RoutedEventArgs e)
{
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
if (e.ChangedButton == MouseButton.Left)
{
DragMove();
e.Handled = true;
}
}
protected override async void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
try
{
await LoadApp();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
private async Task LoadApp()
{
SetProgress(0);
Exception exception = null;
await Task.Run(() =>
{
try
{
LoadDLLs();
SetProgress(15);
}
catch (Exception ex)
{
exception = ex;
}
});
if (exception != null)
{
Debug.WriteLine(exception);
SetError(exception);
}
SetProgress(75);
Application.Current.Dispatcher.Invoke(() =>
{
try
{
CloseCallBack?.Invoke();
}
catch (Exception ex)
{
SetError(ex);
Close();
}
finally
{
SetProgress(100);
}
});
}
private void LoadDLLs()
{
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
}
public void SetProgress(double progress)
{
Dispatcher.Invoke(() =>
{
//Progress.Value = progress;
});
}
private void SetError(Exception ex)
{
ApplicationLogService.WriteFatal(ex, "AppSplashScreen");
}
}
}
@@ -3,16 +3,17 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:dialog="clr-namespace:MAX.Framework.Controls.Attach;assembly=MAX.Framework"
xmlns:f="Store.Management.Framework" xmlns:f="Store.Management.Framework"
xmlns:wpf="MAX.WPF"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:Store.Management.ViewModels" xmlns:vm="clr-namespace:Store.Management.ViewModels"
d:Background="White"
d:DataContext="{d:DesignInstance Type=vm:DataGridTestViewModel}" d:DataContext="{d:DesignInstance Type=vm:DataGridTestViewModel}"
d:DesignHeight="760" d:DesignHeight="760"
d:DesignWidth="1280" d:DesignWidth="1280"
dialog:DialogWindowProperty.Height="800" f:DialogWindowProperty.Height="800"
dialog:DialogWindowProperty.ResizeMode="CanResizeWithGrip" f:DialogWindowProperty.ResizeMode="CanResizeWithGrip"
dialog:DialogWindowProperty.Width="1360" f:DialogWindowProperty.Width="1360"
mc:Ignorable="d"> mc:Ignorable="d">
<UserControl.DataContext> <UserControl.DataContext>
<vm:DataGridTestViewModel /> <vm:DataGridTestViewModel />
@@ -69,15 +70,13 @@
Style="{StaticResource DemoButton}" /> Style="{StaticResource DemoButton}" />
</WrapPanel> </WrapPanel>
<!-- 两种搜索:当前页实时过滤、全部样例模拟后台查询。 --> <!-- 两种搜索:当前页实时过滤、全部样例模拟后台查询。 -->
<WrapPanel Margin="0,10,0,0"> <wpf:SpacingStackPanel Style="{StaticResource TableSearchBarStyle}">
<StackPanel Margin="0,0,24,6" Orientation="Horizontal"> <StackPanel Margin="0,0,16,0" Orientation="Horizontal">
<TextBlock <TextBlock
Margin="0,0,8,0" Margin="0,0,8,0"
VerticalAlignment="Center" VerticalAlignment="Center"
Text="当前页实时搜索" /> Text="当前页实时搜索" />
<TextBox <TextBox
Width="220"
AutomationProperties.Name="当前页实时搜索"
MaxLength="{x:Static vm:DataGridTestViewModel.SearchTextLimit}" MaxLength="{x:Static vm:DataGridTestViewModel.SearchTextLimit}"
Text="{Binding LocalKeyword, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Text="{Binding LocalKeyword, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ToolTip="输入即过滤当前页;清空恢复本页数据,不改变分页总数" /> ToolTip="输入即过滤当前页;清空恢复本页数据,不改变分页总数" />
@@ -86,31 +85,29 @@
VerticalAlignment="Center" VerticalAlignment="Center"
Text="{Binding LocalSearchSummary, Mode=OneWay}" /> Text="{Binding LocalSearchSummary, Mode=OneWay}" />
</StackPanel> </StackPanel>
<StackPanel Margin="0,0,0,6" Orientation="Horizontal"> <StackPanel Margin="0" Orientation="Horizontal">
<TextBlock <TextBlock
Margin="0,0,8,0" Margin="0,0,8,0"
VerticalAlignment="Center" VerticalAlignment="Center"
Text="后台搜索(模拟)" /> Text="后台搜索(模拟)" />
<TextBox <TextBox
Width="220"
AutomationProperties.Name="后台搜索关键字"
MaxLength="{x:Static vm:DataGridTestViewModel.SearchTextLimit}" MaxLength="{x:Static vm:DataGridTestViewModel.SearchTextLimit}"
Text="{Binding BackendKeyword, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Text="{Binding BackendKeyword, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ToolTip="按名称、ID、分组、子账号、手机号、状态或备注搜索全部样例" /> ToolTip="按名称、ID、分组、子账号、手机号、状态或备注搜索全部样例" />
<Button <Button
Margin="8,0,0,0" Margin="8,0,0,0"
Padding="14,3"
Command="{Binding SearchCommand, Mode=OneWay}" Command="{Binding SearchCommand, Mode=OneWay}"
Content="搜索" /> Content="搜索" />
</StackPanel> </StackPanel>
</WrapPanel> </wpf:SpacingStackPanel>
</StackPanel> </StackPanel>
<!-- ItemsSource 是当前页;后台分页时只需替换加载命令。 --> <!-- ItemsSource 是当前页;后台分页时只需替换加载命令。 -->
<f:DataGridEx <f:DataGridEx
x:Name="StoreGrid" x:Name="StoreGrid"
Grid.Row="1" Grid.Row="1"
Margin="10" Margin="10"
d:IsLoading="True" d:IsLoading="false"
BorderThickness="1"
CanUserSortColumns="True" CanUserSortColumns="True"
IsLoading="{Binding LoadingStatus.IsLoading, Mode=OneWay}" IsLoading="{Binding LoadingStatus.IsLoading, Mode=OneWay}"
IsReadOnly="True" IsReadOnly="True"
@@ -126,6 +123,9 @@
ShowRowNumber="True" ShowRowNumber="True"
ShowToolbar="True" ShowToolbar="True"
TotalItemCount="{Binding TotalCount, Mode=OneWay}"> TotalItemCount="{Binding TotalCount, Mode=OneWay}">
<!--<f:DataGridEx.PageSizes>
<Int32Collection>50,100,500,1000</Int32Collection>
</f:DataGridEx.PageSizes>-->
<f:DataGridEx.ToolbarContent> <f:DataGridEx.ToolbarContent>
<ItemsControl> <ItemsControl>
<ItemsControl.ItemsPanel> <ItemsControl.ItemsPanel>
@@ -0,0 +1,42 @@
<UserControl
x:Class="Store.Management.Views.Dialogs.UserBillingDialog"
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:hc="https://handyorg.github.io/handycontrol"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wpf="MAX.WPF"
Width="460"
Height="310"
d:Background="White"
Style="{StaticResource ConfirmDialog}"
mc:Ignorable="d">
<ItemsControl
d:ItemsSource="{d:SampleData ItemCount=5}"
IsEnabled="{Binding EnableConfirm, Mode=OneWay}"
ItemsSource="{Binding Fields, Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<wpf:SpacingStackPanel Style="{StaticResource VerticalSpacingPanel4}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<wpf:TitleContent
Title="{Binding Label, Mode=OneWay}"
Placement="Left"
TitleVerticalAlignment="Center"
TitleWidth="200">
<hc:NumericUpDown
DecimalPlaces="{Binding DecimalPlaces, Mode=OneWay}"
Increment="{Binding Increment, Mode=OneWay}"
Maximum="{Binding Maximum, Mode=OneWay}"
Minimum="{Binding Minimum, Mode=OneWay}"
TextBoxBase.TextChanged="OnAmountTextChanged"
ValueChanged="OnAmountValueChanged"
Value="{Binding Value, Mode=OneWay}" />
</wpf:TitleContent>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</UserControl>
@@ -0,0 +1,128 @@
using Store.Management.Framework.ViewModels;
using Prism.Commands;
using Prism.Services.Dialogs;
using Store.Management.Api.Transport;
using Store.Management.Api.Users;
using Store.Management.Framework.Controls;
using Store.Management.Framework.Services;
using NumericUpDown = HandyControl.Controls.NumericUpDown;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Input;
namespace Store.Management.Views.Dialogs;
public partial class UserBillingDialog : UserControl
{
public UserBillingDialog() => InitializeComponent();
private void OnAmountValueChanged(object sender, HandyControl.Data.FunctionEventArgs<double> e)
{
if (sender is NumericUpDown { IsKeyboardFocusWithin: true, DataContext: UserBillingDialogViewModel.BillingField field })
{
field.Value = (decimal)e.Info;
}
}
private void OnAmountTextChanged(object sender, TextChangedEventArgs e)
{
// 显式输入与控件初始值相同的金额时,Value 不会触发变化。
if (sender is NumericUpDown { IsKeyboardFocusWithin: true, DataContext: UserBillingDialogViewModel.BillingField field }
&& e.OriginalSource is TextBox input
&& decimal.TryParse(input.Text, NumberStyles.Number, CultureInfo.CurrentCulture, out decimal amount)
&& amount == field.Value)
{
field.Value = amount;
}
}
}
public sealed class UserBillingDialogViewModel(IUserService userService) : ConfirmDialogViewModel<UserItemViewModel>
{
public sealed class BillingField(string label, decimal? original, decimal minimum,
Action<UserBillingUpdateRequest, decimal> apply, bool integer = false)
{
private readonly decimal? originalValue = original;
public string Label { get; } = label;
public decimal? EnteredValue { get; private set; } = original;
public decimal Value
{
get => EnteredValue ?? minimum;
set => EnteredValue = value;
}
public decimal Minimum => Math.Min(originalValue ?? minimum, minimum);
public decimal Maximum => Math.Max(originalValue ?? minimum, integer ? int.MaxValue : 999999m);
public int DecimalPlaces => integer ? 0 : 2;
public decimal Increment => integer ? 1m : 0.01m;
internal bool ApplyChange(UserBillingUpdateRequest request)
{
if (EnteredValue is not decimal value || value == originalValue)
{
return false;
}
decimal maximum = integer ? int.MaxValue : 999999m;
if (value < minimum || value > maximum || decimal.Round(value, DecimalPlaces) != value)
{
throw new FormatException($"{Label}范围为 {minimum} 至 {maximum}" + (integer ? ",请输入整数。" : ",最多两位小数。"));
}
apply(request, value);
return true;
}
}
public BillingField[] Fields { get; private set => SetProperty(ref field, value); } = [];
public override void OnDialogOpened(IDialogParameters parameters)
{
base.OnDialogOpened(parameters);
Title = $"计费配置 · {Parameter.UserName}";
Fields =
[
new("店铺每月续费积分(积分/月)", Parameter.ShopPointsPerMonth, 30m, (request, value) => request.ShopPointsPerMonth = (int)value, integer: true),
new("中转仓快递费(元/单)", Parameter.PostagePerOrder, 2.20m, (request, value) => request.PostagePerOrder = value),
new("中转仓退货快递费(元/单)", Parameter.RefundPostagePerOrder, 2.50m, (request, value) => request.RefundPostagePerOrder = value),
new("礼物单附加费(元/单)", Parameter.GiftOemAmountPerOrder, 0m, (request, value) => request.GiftOemAmountPerOrder = value),
new("物流同步费(元/单)", Parameter.SyncLogisticsPerOrder, 0m, (request, value) => request.SyncLogisticsPerOrder = value)
];
}
public override bool CanCloseDialog() => !IsLoading;
public override ICommand ConfirmCommand => field ??= new AsyncDelegateCommand(SaveAsync);
private async Task SaveAsync()
{
var request = new UserBillingUpdateRequest { Id = Parameter.Id };
try
{
bool changed = false;
foreach (BillingField field in Fields)
{
changed |= field.ApplyChange(request);
}
if (!changed)
{
OnRequestClose(new DialogResult(ButtonResult.Cancel));
return;
}
ErrorMsg = "";
IsLoading = true;
await userService.UpdateBillingAsync(request);
}
catch (FormatException ex)
{
ErrorMsg = ex.Message;
return;
}
catch (ApiException ex)
{
ErrorMsg = ex.Message;
return;
}
finally
{
IsLoading = false;
}
OnRequestClose(new DialogResult(ButtonResult.OK));
}
}
@@ -0,0 +1,88 @@
<UserControl
x:Class="Store.Management.Views.LeftNavView"
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:f="Store.Management.Framework"
xmlns:local="clr-namespace:Store.Management.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:Store.Management.ViewModels"
xmlns:wpf="MAX.WPF"
d:Background="White"
d:DataContext="{d:DesignInstance Type=vm:MainViewModel}"
d:DesignHeight="450"
d:Width="255"
Background="White"
mc:Ignorable="d">
<UserControl.Resources>
<wpf:CommandProxy x:Key="NavItemCommand" Command="{Binding NavItemCommand}" />
<Style
x:Key="NavItemButton"
BasedOn="{StaticResource ButtonCustom}"
TargetType="Button">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="{StaticResource PrimaryBrush}" />
</Trigger>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter Property="Foreground" Value="{StaticResource PrimaryBrush}" />
</DataTrigger>
</Style.Triggers>
</Style>
<DataTemplate x:Key="NavItemTemplate" DataType="{x:Type vm:NavItemViewModel}">
<Button
HorizontalContentAlignment="Stretch"
Command="{StaticResource NavItemCommand}"
CommandParameter="{Binding}"
Style="{StaticResource NavItemButton}">
<Button.Content>
<Border
x:Name="NavItemBackground"
Height="45"
Background="Transparent"
BorderBrush="{StaticResource SecondaryBorderBrush}"
BorderThickness="0,0,0,1"
Cursor="Hand">
<Grid>
<StackPanel Orientation="Horizontal">
<f:IconText
Margin="10,0,10,0"
FontSize="18"
Icon="{Binding Icon}" />
<TextBlock
VerticalAlignment="Center"
FontSize="14"
Text="{Binding Title}" />
</StackPanel>
<Border
Margin="0,0,10,0"
HorizontalAlignment="Right"
Visibility="{Binding IsSelected, Converter={StaticResource Boolean2VisibilityConverter}}">
<f:IconText Icon="ChevronRight" />
</Border>
</Grid>
</Border>
</Button.Content>
</Button>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsSelected, Mode=OneWay}" Value="True">
<Setter TargetName="NavItemBackground" Property="Background" Value="{StaticResource SelectedBackgroundBrush}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</UserControl.Resources>
<ItemsControl
d:ItemsSource="{d:SampleData ItemCount=10}"
ItemTemplate="{StaticResource NavItemTemplate}"
ItemsSource="{Binding NavItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<wpf:SpacingStackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</UserControl>
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace Store.Management.Views
{
/// <summary>
/// LeftNavView.xaml 的交互逻辑
/// </summary>
public partial class LeftNavView : UserControl
{
public LeftNavView()
{
InitializeComponent();
}
}
}
+33 -27
View File
@@ -5,10 +5,12 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:Store.Management.ViewModels" xmlns:vm="clr-namespace:Store.Management.ViewModels"
xmlns:wpf="MAX.WPF"
Width="520" Width="520"
Height="620" Height="620"
MinWidth="440" MinWidth="440"
MinHeight="540" MinHeight="540"
d:Background="White"
d:DataContext="{d:DesignInstance Type=vm:LoginViewModel}" d:DataContext="{d:DesignInstance Type=vm:LoginViewModel}"
Background="{DynamicResource BackgroundBrush}" Background="{DynamicResource BackgroundBrush}"
Foreground="{DynamicResource PrimaryTextBrush}" Foreground="{DynamicResource PrimaryTextBrush}"
@@ -20,6 +22,7 @@
<StackPanel MaxWidth="360"> <StackPanel MaxWidth="360">
<!-- 系统标识与登录说明 --> <!-- 系统标识与登录说明 -->
<TextBlock <TextBlock
d:Text="TextBlock"
FontSize="14" FontSize="14"
FontWeight="SemiBold" FontWeight="SemiBold"
Foreground="{DynamicResource PrimaryBrush}" Foreground="{DynamicResource PrimaryBrush}"
@@ -42,33 +45,36 @@
BorderBrush="{DynamicResource BorderBrush}" BorderBrush="{DynamicResource BorderBrush}"
BorderThickness="1" BorderThickness="1"
CornerRadius="8"> CornerRadius="8">
<StackPanel> <wpf:SpacingStackPanel Orientation="Vertical" VerticalSpacing="10">
<Label <ComboBox
Padding="0,0,0,8" wpf:EnumBindingExtension.SelectedEnum="{Binding ee, Mode=TwoWay}"
Content="用户名" ItemsSource="{wpf:EnumBindingMarkup EnumType={x:Type vm:EEE},
Target="{Binding ElementName=UserNameBox, Mode=OneWay}" /> Converter={StaticResource EnumDisplayConverter}}"
<TextBox SelectedValuePath="Value" />
x:Name="UserNameBox" <wpf:TitleContent
Height="40" Title="用户名"
VerticalContentAlignment="Center" Placement="Left"
AutomationProperties.Name="用户名" TitleVerticalAlignment="Center"
IsEnabled="{Binding CanEdit, Mode=OneWay}" TitleWidth="50">
MaxLength="{x:Static vm:LoginViewModel.InputMaxLength}" <TextBox
Text="{Binding UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> VerticalContentAlignment="Center"
<Label IsEnabled="{Binding CanEdit, Mode=OneWay}"
Padding="0,20,0,8" MaxLength="{x:Static vm:LoginViewModel.InputMaxLength}"
Content="密码" Text="{Binding UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
Target="{Binding ElementName=PasswordBox, Mode=OneWay}" /> </wpf:TitleContent>
<PasswordBox
x:Name="PasswordBox"
PasswordChanged="OnPasswordChanged"
Height="40"
VerticalContentAlignment="Center"
AutomationProperties.Name="密码"
IsEnabled="{Binding CanEdit, Mode=OneWay}"
MaxLength="{x:Static vm:LoginViewModel.InputMaxLength}"
/>
<wpf:TitleContent
Title="密码"
Placement="Left"
TitleVerticalAlignment="Center"
TitleWidth="50">
<PasswordBox
x:Name="PasswordBox"
VerticalContentAlignment="Center"
IsEnabled="{Binding CanEdit, Mode=OneWay}"
MaxLength="{x:Static vm:LoginViewModel.InputMaxLength}"
PasswordChanged="OnPasswordChanged" />
</wpf:TitleContent>
<TextBlock <TextBlock
Margin="0,12,0,0" Margin="0,12,0,0"
AutomationProperties.LiveSetting="Polite" AutomationProperties.LiveSetting="Polite"
@@ -91,7 +97,7 @@
Content="{Binding LoginButtonText, Mode=OneWay}" Content="{Binding LoginButtonText, Mode=OneWay}"
IsDefault="True" IsDefault="True"
Style="{StaticResource ButtonPrimary}" /> Style="{StaticResource ButtonPrimary}" />
</StackPanel> </wpf:SpacingStackPanel>
</Border> </Border>
<TextBlock <TextBlock
Margin="0,20,0,0" Margin="0,20,0,0"
@@ -14,7 +14,6 @@ public partial class LoginWindow : UserControl
{ {
viewModel.ClearPasswordRequested += OnClearPasswordRequested; viewModel.ClearPasswordRequested += OnClearPasswordRequested;
} }
UserNameBox.Focus();
} }
private void OnPasswordChanged(object sender, RoutedEventArgs e) private void OnPasswordChanged(object sender, RoutedEventArgs e)
@@ -0,0 +1,13 @@
<UserControl
x:Class="Store.Management.Views.MainHeaderView"
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:local="clr-namespace:Store.Management.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Height="50"
d:Background="White"
d:Width="800"
mc:Ignorable="d">
<Grid />
</UserControl>
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace Store.Management.Views
{
/// <summary>
/// MainHeaderView.xaml 的交互逻辑
/// </summary>
public partial class MainHeaderView : UserControl
{
public MainHeaderView()
{
InitializeComponent();
}
}
}
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more