Compare commits

...
13 Commits
Author SHA1 Message Date
chfei 93b8b404f6 升级 2026-10-27 17:37:42 +08:00
chfei b842292817 合并控件 2026-10-22 13:42:04 +08:00
chfei 233ec5d58d 优化datagrid 2026-10-21 17:11:24 +08:00
chfei e12c419ef3 提交 2026-09-09 15:49:28 +08:00
chfei 11599bc7d3 修改订单列表页UI 2026-09-08 10:09:42 +08:00
wule e4e8c34f8d 发版,一些细节及小bug修改 2026-09-07 17:49:40 +08:00
chfei 39648cd9a9 修改订单详情UI 布局控件 2026-09-07 17:48:36 +08:00
wule f7082d8a7a 修改文字错误 2026-09-07 15:56:22 +08:00
wule b7abfb79c6 发新版 2026-09-07 15:56:22 +08:00
wule 57c8b69252 同上一条 2026-09-07 15:56:22 +08:00
wule 4f1fa75ec8 用户拍单可以通过商品选择sku 2026-09-07 15:56:22 +08:00
chfei a18191b1a6 修复复制 提示错误bug 2026-09-07 15:56:22 +08:00
wule 4e449f31bd 订单增加礼物单退费显示 2026-09-07 15:56:22 +08:00
34 changed files with 3018 additions and 1048 deletions

No files matched your search

@@ -0,0 +1,128 @@
<UserControl
x:Class="_29WxOrderWpf.Ctrls.BuyerCtrls.SkuSelectListRowCtrl"
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:_29WxOrderWpf.Ctrls.BuyerCtrls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="150"
d:DesignWidth="800"
mc:Ignorable="d">
<Grid>
<Border
Margin="4"
BorderBrush="LightSkyBlue"
BorderThickness="1"
CornerRadius="10">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<Image
x:Name="imgSku"
Grid.Row="0"
Grid.Column="0"
Width="100"
Height="100"
Margin="8"
VerticalAlignment="Top"
Cursor="Hand"
MouseDown="imgSku_MouseDown"
MouseEnter="imgSku_MouseEnter"
MouseLeave="imgSku_MouseLeave" />
<Grid
Grid.Column="1"
Margin="0,8"
VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<WrapPanel Visibility="{Binding SpecNameStr, Converter={StaticResource HasTextVisibility}}">
<TextBox
VerticalAlignment="Top"
d:Opacity="0.5"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="商品标题:"
TextWrapping="Wrap" />
<TextBox
VerticalAlignment="Top"
d:Opacity="0.5"
d:Text="商品标题"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding GoodsNameStr}"
TextWrapping="Wrap" />
</WrapPanel>
<WrapPanel Grid.Row="1" Visibility="{Binding SpecNameStr, Converter={StaticResource HasTextVisibility}}">
<TextBox
VerticalAlignment="Top"
d:Opacity="0.5"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="商品规格:"
TextWrapping="Wrap" />
<TextBox
Grid.Row="0"
VerticalAlignment="Top"
d:Opacity="0.5"
d:Text="SKU规格"
Background="Transparent"
BorderThickness="0"
FontWeight="Bold"
IsReadOnly="True"
Text="{Binding SpecNameStr}"
TextWrapping="Wrap" />
</WrapPanel>
<WrapPanel Grid.Row="2" Visibility="{Binding groupPrice, Converter={StaticResource HasTextVisibility}}">
<TextBox
VerticalAlignment="Top"
d:Opacity="0.5"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="规格单价:"
TextWrapping="Wrap" />
<TextBox
Grid.Row="0"
VerticalAlignment="Top"
d:Opacity="0.5"
d:Text="0.00"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding groupPrice}"
TextWrapping="Wrap" />
</WrapPanel>
</Grid>
<Button
x:Name="btnAdd"
Grid.Column="100"
MinWidth="48"
MinHeight="28"
Margin="8"
Padding="4"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Click="btnAdd_Click"
Content="确定关联"
Style="{StaticResource BasePageButtonStyle}" />
</Grid>
</Border>
</Grid>
</UserControl>
@@ -0,0 +1,81 @@
using _29WxOrderWpf.ViewModels;
using AllBase;
using AllBase.Model.DBModel;
using AllBase.Model.Result;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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;
using Work._29Tools.Forms.ToolForms;
namespace _29WxOrderWpf.Ctrls.BuyerCtrls;
/// <summary>
/// SkuSelectListRowCtrl.xaml 的交互逻辑
/// </summary>
public partial class SkuSelectListRowCtrl : UserControl
{
public SkuSelectListRowCtrl()
{
InitializeComponent();
this.DataContextChanged += SkuSelectListRowCtrl_DataContextChanged;
}
private void SkuSelectListRowCtrl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (this.DataContext is frontSkuInfo3 frontSku)
{
Task.Run(() =>
{
// 异步加载图片防止卡顿
// 缩略图在有的电脑上无法显示
//BitmapImage bImg = ImageUrlToBitmapImageConverter.LoadImageFromUrl(order_item.thumb_img + "?imageView2/1/w/100/format/webp|imageMogr2/auto-orient=");
BitmapImage bImg = AllBase.ImageBuild.LoadBitmipImageFromUrl(frontSku.thumbUrl);
Thread.Sleep(Randomx.GetId(200));
Dispatcher.Invoke(new Action(() =>
{
imgSku.Source = bImg;
}));
});
}
}
private void imgSku_MouseDown(object sender, MouseButtonEventArgs e)
{
if (this.DataContext is frontSkuInfo3 frontSku)
{
ShowImgForm imgFrom = new ShowImgForm(frontSku.thumbUrl);
imgFrom.TopMost = true;
imgFrom.Show();
}
}
private void imgSku_MouseEnter(object sender, MouseEventArgs e)
{
}
private void imgSku_MouseLeave(object sender, MouseEventArgs e)
{
}
private async void btnAdd_Click(object sender, RoutedEventArgs e)
{
if (this.DataContext is frontSkuInfo3 frontSku)
{
await BuyMapSkuViewModel.BuyMapSkuInstance.SetOrderMapSku(frontSku);
}
}
}
@@ -580,24 +580,33 @@
BorderThickness="0,0,0,1"> BorderThickness="0,0,0,1">
<WrapPanel> <WrapPanel>
<CheckBox <CheckBox
x:Name="chkMapProdOnly" x:Name="chkNoMapProd"
Margin="8,0,4,0" Margin="8,0,4,0"
HorizontalAlignment="Left" HorizontalAlignment="Left"
VerticalAlignment="Center" VerticalAlignment="Center"
BorderBrush="{StaticResource mainColorBrush}" BorderBrush="{StaticResource mainColorBrush}"
Click="chkMapProdOnly_Click" Click="chkMapProd_Click"
Content="已关联拍单"
FontSize="12" />
<CheckBox
x:Name="chkNoMapProdOnly"
Margin="8,0,4,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
BorderBrush="{StaticResource mainColorBrush}"
Click="chkNoMapProdOnly_Click"
Content="未关联拍单" Content="未关联拍单"
FontSize="12" /> FontSize="12" />
<CheckBox
x:Name="chkMapProd"
Margin="8,0,4,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
BorderBrush="{StaticResource mainColorBrush}"
Click="chkMapProd_Click"
Content="已关联商品"
FontSize="12" />
<CheckBox
x:Name="chkMapSku"
Margin="8,0,4,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
BorderBrush="{StaticResource mainColorBrush}"
Click="chkMapProd_Click"
Content="已关联拍单"
FontSize="12" />
<Button <Button
Width="Auto" Width="Auto"
@@ -1512,9 +1512,11 @@ namespace _29WxOrderWpf.Ctrls.OrderCtrls
{ {
if (!order.IsWaitBuy) if (!order.IsWaitBuy)
return true; return true;
if (chkMapProdOnly.IsChecked == true && order.orderItems.All(oi => oi.BuyMap == null)) if (chkMapSku.IsChecked == true && order.orderItems.All(oi => oi.BuyMap == null && (oi.BuyMapSkus == null || oi.BuyMapSkus.Count == 0)))
return true; return true;
if (chkNoMapProdOnly.IsChecked == true && order.orderItems.All(oi => oi.BuyMap != null)) if (chkMapProd.IsChecked == true && order.orderItems.All(oi => oi.BuyMapSkus == null || oi.BuyMapSkus.Count == 0))
return true;
if (chkNoMapProd.IsChecked == true && order.orderItems.All(oi => oi.BuyMap != null))
return true; return true;
} }
if (filterHeadStr.StartsWith("待发货")) if (filterHeadStr.StartsWith("待发货"))
@@ -1821,16 +1823,14 @@ namespace _29WxOrderWpf.Ctrls.OrderCtrls
FilterOrders(); FilterOrders();
} }
private void chkMapProdOnly_Click(object sender, RoutedEventArgs e) private void chkMapProd_Click(object sender, RoutedEventArgs e)
{ {
if (chkMapProdOnly.IsChecked == true) if (sender is CheckBox chk)
chkNoMapProdOnly.IsChecked = false; {
FilterOrders(); var isCheck = !chk.IsChecked.ParseToBool();
chkNoMapProd.IsChecked = chkMapProd.IsChecked = chkMapSku.IsChecked = false;
chk.IsChecked = !isCheck;
} }
private void chkNoMapProdOnly_Click(object sender, RoutedEventArgs e)
{
if (chkNoMapProdOnly.IsChecked == true)
chkMapProdOnly.IsChecked = false;
FilterOrders(); FilterOrders();
} }
@@ -1,14 +1,21 @@
<UserControl x:Class="_29WxOrderWpf.Ctrls.OrderCtrls.OrderListRowCtrl" <UserControl
x:Class="_29WxOrderWpf.Ctrls.OrderCtrls.OrderListRowCtrl"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:_29WxOrderWpf.Ctrls.OrderCtrls" xmlns:local="clr-namespace:_29WxOrderWpf.Ctrls.OrderCtrls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:uc="clr-namespace:_29WxOrderWpf.UserControls" xmlns:uc="clr-namespace:_29WxOrderWpf.UserControls"
mc:Ignorable="d" d:DesignHeight="230"
d:DesignHeight="230" d:DesignWidth="1200"> d:DesignWidth="1200"
<Border Margin="0,12,8,0" HorizontalAlignment="Stretch" VerticalAlignment="Center" BorderThickness="1" mc:Ignorable="d">
BorderBrush="{StaticResource ListRowBorderColorBrush}" CornerRadius="10"> <Border
Margin="0,12,8,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
BorderBrush="{StaticResource ListRowBorderColorBrush}"
BorderThickness="1"
CornerRadius="10">
<Border.Style> <Border.Style>
<!-- 鼠标进入或悬停Border时切换颜色(悬停时Border的填充控件必须有填充Border,所在层级不限,仅填充透明Grid则触发器无效) --> <!-- 鼠标进入或悬停Border时切换颜色(悬停时Border的填充控件必须有填充Border,所在层级不限,仅填充透明Grid则触发器无效) -->
<Style TargetType="Border"> <Style TargetType="Border">
@@ -21,19 +28,22 @@
</Border.Style> </Border.Style>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Center"> <Grid HorizontalAlignment="Stretch" VerticalAlignment="Center">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto" />
<RowDefinition Height="*"></RowDefinition> <RowDefinition Height="*" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<!-- 子控件是普通控件而非模板页控件,无需指定DataContext="{Binding}" --> <!-- 子控件是普通控件而非模板页控件,无需指定DataContext="{Binding}" -->
<local:OrderListRowHeaderCtrl></local:OrderListRowHeaderCtrl> <local:OrderListRowHeaderCtrl />
<!--<local:OrderListRowHeaderCtrl DataContext="{Binding}"></local:OrderListRowHeaderCtrl>--> <!--<local:OrderListRowHeaderCtrl DataContext="{Binding}"></local:OrderListRowHeaderCtrl>-->
<Border Grid.Row="1" Background="Transparent" CornerRadius="0,0,12,12" > <Border
Grid.Row="1"
Background="Transparent"
CornerRadius="0,0,12,12">
<Grid x:Name="gridChildOrder"> <Grid x:Name="gridChildOrder">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="6"></RowDefinition> <RowDefinition Height="6" />
<RowDefinition Height="auto"></RowDefinition> <RowDefinition Height="auto" />
<RowDefinition Height="6"></RowDefinition> <RowDefinition Height="6" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
</Grid> </Grid>
</Border> </Border>
File diff suppressed because it is too large. Load diff
@@ -50,12 +50,13 @@ namespace _29WxOrderWpf.Ctrls.OrderCtrls
public OrderListRowItemCtrl() public OrderListRowItemCtrl()
{ {
InitializeComponent(); InitializeComponent();
txtTransitOrderBuyerStr.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtTransitOrderNumStr_MouseLeftButtonUp), true); txtTransitOrderBuyerStr.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(TransitOrderBuye_Click), true);
txtTransitOrderNumStr.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtTransitOrderNumStr_MouseLeftButtonUp), true); txtTransitOrderNumStr.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(TransitOrderBuye_Click), true);
txtDirectBuyer.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtDirectOrderNumStr_MouseLeftButtonUp), true); txtDirectBuyer.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtDirectOrderNumStr_MouseLeftButtonUp), true);
txtDirectBuyerOrderNo.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtDirectOrderNumStr_MouseLeftButtonUp), true); txtDirectBuyerOrderNo.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtDirectOrderNumStr_MouseLeftButtonUp), true);
txtRefundId.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtRefundId_MouseLeftButtonUp), true); txtRefundId.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtRefundId_MouseLeftButtonUp), true);
txtWarehouseStatus.AddHandler(TextBox.MouseEnterEvent, new MouseEventHandler(txtWarehouseStatus_MouseEnter), true); txtWarehouseStatus.AddHandler(TextBox.MouseEnterEvent, new MouseEventHandler(txtWarehouseStatus_MouseEnter), true);
} }
@@ -716,11 +717,10 @@ namespace _29WxOrderWpf.Ctrls.OrderCtrls
return true; return true;
} }
private void TransitOrderBuye_Click(object sender, MouseButtonEventArgs e)
private void txtTransitOrderNumStr_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{ {
var buyerName = txtTransitOrderBuyerStr.Text.Split(':').LastOrDefault(); var buyerName = txtTransitOrderBuyerStr.Text;
var outOrderId = txtTransitOrderNumStr.Text.Split(':').LastOrDefault(); var outOrderId = txtTransitOrderNumStr.Text;
if (string.IsNullOrEmpty(buyerName) || string.IsNullOrEmpty(outOrderId)) if (string.IsNullOrEmpty(buyerName) || string.IsNullOrEmpty(outOrderId))
{ {
return; return;
@@ -1585,6 +1585,18 @@ namespace _29WxOrderWpf.Ctrls.OrderCtrls
} }
} }
private void btnMapSkus_Click(object sender, RoutedEventArgs e)
{
if (DataContext is oms_wei_order_item_info orderItem)
{
BuyMapSkuSelectWindow window = new BuyMapSkuSelectWindow(orderItem);
window.Show();
}
}
} }
} }
@@ -1,4 +1,5 @@
using _29WxOrderWpf.Ctrls.Statistics.Models; using _29WxOrderWpf.BaseWindows;
using _29WxOrderWpf.Ctrls.Statistics.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -36,7 +37,16 @@ public partial class ShowOrderDialogView : UserControl
&& element.DataContext is ShopRevenueStatisticsRow row && element.DataContext is ShopRevenueStatisticsRow row
&& !string.IsNullOrEmpty(row.OrderId)) && !string.IsNullOrEmpty(row.OrderId))
{ {
Clipboard.SetText(row.OrderId); Window window = Window.GetWindow(this);
try
{
Clipboard.SetDataObject(row.OrderId);
BaseMsgWindow.ShowAnimateMessage("复制成功");
}
catch (Exception ex)
{
BaseMsgWindow.ShowError("复制失败 " + ex.Message,window: window);
}
} }
} }
} }
@@ -0,0 +1,237 @@
using _29WxOrderWpf.BaseWindows;
using _29WxOrderWpf.Commands;
using AllBase;
using AllBase.Helper;
using AllBase.Model.DBModel;
using AllBase.Model.MvvmBaseClasses;
using AllBase.Model.Result;
using NaiBa.Util.Extension;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.Record;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Work;
using Work.BaseForms;
using Work.SearchSame;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
namespace _29WxOrderWpf.ViewModels;
public class BuyMapSkuViewModel : PropertyNotifyObject
{
public static BuyMapSkuViewModel BuyMapSkuInstance { get; set; }
/// <summary>
/// 请求关闭窗口
/// </summary>
public event Action RequestClose;
private volatile bool _isWindowLoaded = false;
public oms_wei_order_item_info OrderItem
{
get { return this.GetValue(x => x.OrderItem); }
set { this.SetValue(x => x.OrderItem, value); }
}
public ObservableCollection<WXBuyMapSkusInfo> BuyMapSkus
{
get { return this.GetValue(x => x.BuyMapSkus); }
set { this.SetValue(x => x.BuyMapSkus, value); }
}
public ObservableCollection<frontSkuInfo3> FrontSkuInfos
{
get { return this.GetValue(x => x.FrontSkuInfos); }
set { this.SetValue(x => x.FrontSkuInfos, value); }
}
public string ShopGoodsName
{
get { return this.GetValue(x => x.ShopGoodsName); }
set { this.SetValue(x => x.ShopGoodsName, value); }
}
public string ShopSkuName
{
get { return this.GetValue(x => x.ShopSkuName); }
set { this.SetValue(x => x.ShopSkuName, value); }
}
public string ShopSkuPrice
{
get { return this.GetValue(x => x.ShopSkuPrice); }
set { this.SetValue(x => x.ShopSkuPrice, value); }
}
//pddFrontGoods3Lite
public BuyMapSkuViewModel(oms_wei_order_item_info orderItem)
{
if (BuyMapSkuInstance != null)
BuyMapSkuInstance.RequestClose.Invoke();
BuyMapSkuInstance = this;
OrderItem = orderItem;
if (orderItem != null)
{
this.ShopGoodsName = orderItem.title;
this.ShopSkuName = orderItem.sku_attr_str;
this.ShopSkuPrice = (orderItem.real_price * 0.01m).ParseToString();
}
if (orderItem?.BuyMapSkus != null && orderItem?.BuyMapSkus.Count > 0)
{
BuyMapSkus = new ObservableCollection<WXBuyMapSkusInfo>(orderItem.BuyMapSkus);
SetCurrentFrontSkuInfo3(BuyMapSkus?.FirstOrDefault());
}
}
public void SetCurrentFrontSkuInfo3(WXBuyMapSkusInfo skuInfo)
{
foreach (var info in BuyMapSkus)
{
info.IsChecked = false;
}
skuInfo.IsChecked = true;
FrontSkuInfos = new ObservableCollection<frontSkuInfo3>(skuInfo?.pdd_front_goods3_Lite.skus);
}
/// <summary>
/// 窗口加载完成时调用
/// </summary>
public void Start()
{
_isWindowLoaded = true;
Task.Run(() =>
{
// todo get skus
});
}
/// <summary>
/// 窗口关闭时调用,停止后台任务
/// </summary>
public void Stop()
{
_isWindowLoaded = false;
}
public async Task SetOrderMapSku(frontSkuInfo3 upSku)
{
var mapSkuProd = OrderItem.BuyMapSkus.FirstOrDefault(s => s.map_goods_id == upSku.goodsId.ParseToString());
if (mapSkuProd == null)
return;
var mapSku = mapSkuProd.pdd_front_goods3_Lite.skus.FirstOrDefault(s => string.Join(",", s.specs.Select(sp => sp.spec_value)) == upSku.SpecNameStr);
if (mapSku == null)
return;
var mapGoodsName = mapSkuProd.map_goods_name;
var mapSkuName = string.Join(",", mapSku.specs.Select(sp => sp.spec_value));
var mapGoodsId = mapSkuProd.map_goods_id;
var mapSkuId = mapSku.skuId.ParseToString();
var sendProvince = mapSkuProd.map_send_address;
string cmbTransitWarehouse = "";
string txtBuyTransitWarehouse = "";
var transitWarehouse = TransitWarehouseData.TransitWarehouseList.FirstOrDefault(t => t.TransId == mapSkuProd.transit_warehouse_id);
if (transitWarehouse != null)
{
cmbTransitWarehouse = transitWarehouse?.TransName + " " + transitWarehouse?.TransDetailAddress;
txtBuyTransitWarehouse = transitWarehouse?.TransDetailAddress;
}
var spuCode = OrderItem.out_product_id.IsNullOrEmpty() ? OrderItem.product_id : OrderItem.out_product_id;
var skuCode = OrderItem.out_sku_id.IsNullOrEmpty() ? OrderItem.sku_attr_str : OrderItem.out_sku_id;
if (spuCode.IsNullOrEmpty())
spuCode = OrderItem.product_id;
if (await SaveSkuMap(spuCode, skuCode, mapGoodsName, mapSkuName, mapGoodsId, mapSkuId, transitWarehouse, sendProvince))
RequestClose?.Invoke();
}
public async Task<bool> SaveSkuMap(string spuCode, string skuCode, string mapGoodsName,
string mapSkuName, string mapGoodsId, string mapSkuId, TransitWarehouseParam transitWarehouse, string sendProvince)
{
if (transitWarehouse == null)
{
BaseMsgForm.ShowError("仓库不能为空");
return false;
}
string url;
string upSpuCode = spuCode;
string upSkuCode = skuCode;
var data = UserLogin.GetSignaturex()
+ "&spu_code=" + GetHtml.UrlEncodeUtf8(upSpuCode)
+ "&sku_code=" + GetHtml.UrlEncodeUtf8(upSkuCode)
+ "&main_user_name=" + BaseClass.MainUserName
+ "&map_goods_name=" + mapGoodsName
+ "&map_spec_name=" + mapSkuName
+ "&map_goods_id=" + mapGoodsId
+ "&map_sku_id=" + mapSkuId
+ "&map_send_address=" + sendProvince
+ "&transit_warehouse_id=" + transitWarehouse?.TransId;
url = BaseClass.Build29WxObjString("order/wx_add_mdy_buy_prod_map");
var result = await GetHtml.PostUtf8Async(url, data);
if (!result.Contains("\"code\":200"))
result = await GetHtml.PostUtf8Async(url, data);
if (!result.Contains("\"code\":200"))
{
BaseMsgForm.ShowError("保存失败" + BaseRegex.GetStringJson(ref result, "msg") + ",请稍后重试");
return false;
}
else
{
var urlMap = BaseClass.Build29WxObjString("order/wx_get_buy_prod_map");
var dataMap = UserLogin.GetSignaturex()
+ "&spu_codes=" + upSpuCode;
//dataMap += "&sku_codes=" + upSkuCode;
dataMap += "&main_user_name=" + BaseClass.MainUserName;
var resultMap = await GetHtml.PostUtf8Async(urlMap, dataMap);
if (string.IsNullOrEmpty(resultMap) || !resultMap.Contains("\"code\":200"))
resultMap = await GetHtml.PostUtf8Async(urlMap, dataMap);
if (string.IsNullOrEmpty(resultMap) || !resultMap.Contains("\"code\":200"))
{
}
else
{
List<WXBuyMapInfo> buyMapList = new List<WXBuyMapInfo>();
try
{
buyMapList = JsonHelper.DeserializeJsonToList<WXBuyMapInfo>(JObject.Parse(resultMap)["data"].ParseToString());
GlobalConfig.BuyMapList.RemoveAll(b => buyMapList.Any(map => b.spu_code == map.spu_code && b.sku_code == map.sku_code));
GlobalConfig.BuyMapList.AddRange(buyMapList);
}
catch
{
}
var map = buyMapList.FirstOrDefault(b => b.spu_code == upSpuCode && b.sku_code == upSkuCode);
if (map != null)
{
foreach (var order in GlobalConfig.lstOrder)
{
if (order.IsWaitBuy)
{
foreach (var item in order.orderItems)
{
if ((item.out_product_id == map.spu_code && item.out_sku_id == map.sku_code) ||
(item.out_product_id == map.spu_code && item.sku_attr_str == map.sku_code) ||
(item.product_id == map.spu_code && item.out_sku_id == map.sku_code) ||
(item.product_id == map.spu_code && item.sku_attr_str == map.sku_code))
{
item.BuyMap = map;
item.SetOrderItemTextProperty();
// todo 此处刷新一条可能不够
MainWindow.Instance.orderListCtrl.FilterOneOrder(order, false);
}
}
}
}
}
}
BaseMsgWindow.ShowInfo("保存成功!");
return true;
}
}
}
@@ -0,0 +1,347 @@
<basewindows:BaseWindow
x:Class="_29WxOrderWpf.Windows.OrderWindows.BuyMapSkuSelectWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:basewindows="clr-namespace:_29WxOrderWpf.BaseWindows"
xmlns:buyerctrls="clr-namespace:_29WxOrderWpf.Ctrls.BuyerCtrls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:_29WxOrderWpf.Windows.OrderWindows"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:skudata="clr-namespace:AllBase.Model.Result;assembly=29WxOrderAllBase"
xmlns:userctrls="clr-namespace:_29WxOrderWpf.UserControls"
Title="SkuSelectWindow"
Width="1360"
Height="768"
d:Height="700"
d:Width="1200"
FontSize="15"
Loaded="SkuSelectWindow_Loaded"
ResizeMode="NoResize"
Style="{StaticResource BaseNoneBorderWindowStyle}"
mc:Ignorable="d">
<Window.Resources>
<!--<x:Array x:Key="frontSkuInfo" Type="skudata:frontSkuInfo3">
<skudata:frontSkuInfo3 />
</x:Array>-->
</Window.Resources>
<Grid
x:Name="mainGrid"
Margin="2"
Background="Transparent"
MouseLeftButtonDown="gridTitle_MouseLeftButtonDown">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid x:Name="gridTitle">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Image
Width="50"
Height="50"
Margin="4"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Source="{StaticResource main29WeixinIcon}" />
<Label
x:Name="lblAppName"
Grid.Column="1"
Margin="0,0,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
Content="选择SKU规格"
FontSize="20"
Foreground="{StaticResource mainColorLightBrush}" />
</Grid>
<Border
Grid.Row="1"
Padding="40,20"
Background="White">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" MinHeight="50" />
<RowDefinition Height="Auto" MinHeight="50" />
<RowDefinition Height="*" MinHeight="50" />
<RowDefinition Height="Auto" MinHeight="50" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" MinWidth="100" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Row="0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
FontSize="15"
Text="订单商品:" />
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Image
x:Name="imgSku"
Grid.Row="0"
Grid.Column="0"
Width="100"
Height="100"
Margin="8"
VerticalAlignment="Top"
Cursor="Hand"
MouseDown="imgSku_MouseDown"
MouseEnter="imgSku_MouseEnter"
MouseLeave="imgSku_MouseLeave" />
<Grid
Grid.Column="1"
Margin="0,8"
VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<WrapPanel Visibility="{Binding ShopGoodsName, Converter={StaticResource HasTextVisibility}}">
<TextBox
VerticalAlignment="Top"
d:Opacity="0.5"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="店铺商品标题:"
TextWrapping="Wrap" />
<TextBox
VerticalAlignment="Top"
d:Opacity="0.5"
d:Text="店铺商品标题"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding ShopGoodsName}"
TextWrapping="Wrap" />
</WrapPanel>
<WrapPanel Grid.Row="1" Visibility="{Binding ShopSkuName, Converter={StaticResource HasTextVisibility}}">
<TextBox
VerticalAlignment="Top"
d:Opacity="0.5"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="店铺商品规格:"
TextWrapping="Wrap" />
<TextBox
Grid.Row="0"
VerticalAlignment="Top"
d:Opacity="0.5"
d:Text="店铺SKU规格"
Background="Transparent"
BorderThickness="0"
FontWeight="Bold"
IsReadOnly="True"
Text="{Binding ShopSkuName}"
TextWrapping="Wrap" />
</WrapPanel>
<WrapPanel Grid.Row="2" Visibility="{Binding ShopSkuPrice, Converter={StaticResource HasTextVisibility}}">
<TextBox
VerticalAlignment="Top"
d:Opacity="0.5"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="店铺规格单价:"
TextWrapping="Wrap" />
<TextBox
Grid.Row="0"
VerticalAlignment="Top"
d:Opacity="0.5"
d:Text="0.00"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding ShopSkuPrice}"
TextWrapping="Wrap" />
</WrapPanel>
</Grid>
</Grid>
<TextBlock
Grid.Row="1"
HorizontalAlignment="Center"
VerticalAlignment="Top"
FontSize="15"
Text="关联商品:" />
<Grid Grid.Row="1" Grid.Column="1">
<ListBox
x:Name="lbxOrderItem"
Grid.Row="1"
Grid.Column="1"
Margin="7,0,7,0"
HorizontalContentAlignment="Stretch"
BorderThickness="0"
ItemsSource="{Binding BuyMapSkus}"
ScrollViewer.CanContentScroll="True"
VirtualizingPanel.ScrollUnit="Pixel">
<!-- 使用自定义属性模板去除ListBox高亮显示框 -->
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentPresenter
Content="{TemplateBinding Content}"
ContentStringFormat="{TemplateBinding ContentStringFormat}"
ContentTemplate="{TemplateBinding ContentTemplate}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<!-- 此处绑定将数据源传递给子自定义控件OrderListRowCtrl -->
<!--<buyerctrls:SkuSelectListRowCtrl
VerticalAlignment="Center"
VerticalContentAlignment="Center"
DataContext="{Binding}" />-->
<RadioButton
MaxWidth="250"
Margin="0,0,12,0"
Click="RadioButton_Click"
IsChecked="{Binding IsChecked}">
<TextBox
VerticalAlignment="Top"
d:Opacity="0.5"
d:Text="商品标题"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding map_goods_name}"
TextWrapping="Wrap" />
</RadioButton>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<!-- 单行横向,超出部分隐藏或滚动 -->
<StackPanel IsItemsHost="True" Orientation="Horizontal" />
<!-- 若需自动换行,替换为以下 WrapPanel -->
<!-- <WrapPanel Orientation="Horizontal" IsItemsHost="True"/> -->
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</Grid>
<TextBlock
Grid.Row="2"
HorizontalAlignment="Center"
VerticalAlignment="Top"
FontSize="15"
Text="选择SKU:" />
<ListBox
x:Name="lbxSku"
Grid.Row="2"
Grid.Column="1"
Margin="7,0,7,0"
HorizontalContentAlignment="Stretch"
BorderThickness="0"
ItemsSource="{Binding FrontSkuInfos}"
ScrollViewer.CanContentScroll="True"
VirtualizingPanel.ScrollUnit="Pixel">
<!-- 使用自定义属性模板去除ListBox高亮显示框 -->
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentPresenter
Content="{TemplateBinding Content}"
ContentStringFormat="{TemplateBinding ContentStringFormat}"
ContentTemplate="{TemplateBinding ContentTemplate}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<!-- 此处绑定将数据源传递给子自定义控件OrderListRowCtrl -->
<buyerctrls:SkuSelectListRowCtrl
VerticalAlignment="Center"
VerticalContentAlignment="Center"
DataContext="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button
x:Name="btnAdd"
Grid.Row="3"
Grid.Column="1"
MinWidth="48"
MinHeight="28"
Padding="4"
HorizontalAlignment="Left"
VerticalAlignment="Center"
d:Visibility="Visible"
Click="btnAdd_Click"
Content="添 加"
Style="{StaticResource BasePageButtonStyle}"
Visibility="Collapsed" />
<Image
x:Name="imgLoading"
Grid.Row="9"
Grid.Column="1"
Width="20"
Height="20"
Margin="52,0,0,0"
HorizontalAlignment="Left"
d:Visibility="Visible"
IsEnabled="False"
Source="{StaticResource imgLoadingPic}"
Visibility="Collapsed">
<Image.RenderTransform>
<RotateTransform Angle="45" CenterX="10" CenterY="10" />
</Image.RenderTransform>
<Image.Triggers>
<EventTrigger RoutedEvent="Image.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
RepeatBehavior="Forever"
Storyboard.TargetName="imgLoading"
Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)"
From="0"
To="360"
Duration="0:0:3" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Image.Triggers>
</Image>
<Label
x:Name="lblMsg"
Grid.Row="9"
Grid.Column="1"
Margin="70,0,0,0"
Foreground="{StaticResource PageWarningBrushCC}" />
</Grid>
</Border>
<userctrls:UcWindowBoxes
x:Name="ucWindowBox"
Margin="4"
HorizontalAlignment="Right"
VerticalAlignment="Top"
MaxBoxVisibility="Visible" />
</Grid>
</basewindows:BaseWindow>
@@ -0,0 +1,117 @@
using _29WxOrderWpf.BaseWindows;
using _29WxOrderWpf.ViewModels;
using AllBase;
using AllBase.Helper;
using AllBase.Model.Config;
using AllBase.Model.DBModel;
using AllBase.Model.Result;
using NaiBa.Util.Extension;
using Newtonsoft.Json.Linq;
using NPOI.POIFS.NIO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
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.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Work._29Tools.BLL;
using Work._29Tools.Forms.ToolForms;
namespace _29WxOrderWpf.Windows.OrderWindows
{
/// <summary>
/// SkuSelectWindow.xaml 的交互逻辑
/// </summary>
public partial class BuyMapSkuSelectWindow : BaseWindow
{
public oms_wei_order_item_info OrderItem { get; set; }
public BuyMapSkuViewModel ViewModel { get; set; } = null;
public BuyMapSkuSelectWindow(oms_wei_order_item_info orderItem)
{
InitializeComponent();
if (orderItem != null)
OrderItem = orderItem;
ViewModel = new BuyMapSkuViewModel(orderItem);
this.DataContext = ViewModel;
ViewModel.RequestClose += ViewModel_RequestClose;
}
private void ViewModel_RequestClose()
{
this.Close();
}
private async void SkuSelectWindow_Loaded(object sender, RoutedEventArgs e)
{
btnAdd.IsEnabled = true;
await Task.Run(() =>
{
// 异步加载图片防止卡顿
// 缩略图在有的电脑上无法显示
//BitmapImage bImg = ImageUrlToBitmapImageConverter.LoadImageFromUrl(order_item.thumb_img + "?imageView2/1/w/100/format/webp|imageMogr2/auto-orient=");
BitmapImage bImg = AllBase.ImageBuild.LoadBitmipImageFromUrl(OrderItem.thumb_img);
Thread.Sleep(Randomx.GetId(200));
Dispatcher.Invoke(new Action(() =>
{
imgSku.Source = bImg;
}));
});
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
}
private void gridTitle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
this.DragMove();
}
}
private void RadioButton_Click(object sender, RoutedEventArgs e)
{
if (this.IsLoaded && sender is RadioButton rb)
{
if (rb.DataContext is WXBuyMapSkusInfo skuInfo)
{
this.ViewModel.SetCurrentFrontSkuInfo3(skuInfo);
}
}
}
private void imgSku_MouseDown(object sender, MouseButtonEventArgs e)
{
ShowImgForm imgFrom = new ShowImgForm(this.OrderItem?.thumb_img);
imgFrom.TopMost = true;
imgFrom.Show();
}
private void imgSku_MouseEnter(object sender, MouseEventArgs e)
{
}
private void imgSku_MouseLeave(object sender, MouseEventArgs e)
{
}
}
}
+1 -1
View File
@@ -36,7 +36,7 @@ namespace AllBase
/// 版本ID /// 版本ID
/// </summary> /// </summary>
public static int VersionCount = 269; public static int VersionCount = 276;
public static string ServerUrl { get; set; } = "http://1.13.195.131:9000"; public static string ServerUrl { get; set; } = "http://1.13.195.131:9000";
public static string DebugUrl { get; set; } = "http://localhost:9000"; public static string DebugUrl { get; set; } = "http://localhost:9000";
@@ -45,8 +45,8 @@ XDYGZC ;广州仓 ;何外华 ;13826339849 ;广州市从化区太平镇
XDYWHC ;武汉2仓 ;杨先生 ;13044121071 ;湖北省武汉市汉阳区洲头街道汉新大道2号3栋17楼 ;13 ;180 ;1548 ;湖北省 ;武汉市 XDYWHC ;武汉2仓 ;杨先生 ;13044121071 ;湖北省武汉市汉阳区洲头街道汉新大道2号3栋17楼 ;13 ;180 ;1548 ;湖北省 ;武汉市
XDYSHANDC ;山东2仓 ;鸿鹄小申 ;13044121239 ;山东省临沂市费县南外环东转盘往东200米顺通快递有限公司(仓库二楼) ;22 ;292 ;2415 ;山东省 ;临沂市 XDYSHANDC ;山东2仓 ;鸿鹄小申 ;13044121239 ;山东省临沂市费县南外环东转盘往东200米顺通快递有限公司(仓库二楼) ;22 ;292 ;2415 ;山东省 ;临沂市
XDYSHC ;上海新仓 ;纪先生 ;13044121150 ;上海市上海市普陀区真如镇街道真北路2653弄T区 ;25 ;321 ;2709 ;上海市 ;上海市 XDYSHC ;上海新仓 ;纪先生 ;13044121150 ;上海市上海市普陀区真如镇街道真北路2653弄T区 ;25 ;321 ;2709 ;上海市 ;上海市
XDYSZC ;深圳仓 ;峰峰 ;15343351331 ;广东省东莞市凤岗镇浸校塘东良巷逸乐轩E栋5号楼 ;6 ;79 ;732 ;广东省 ;东莞市"; XDYSZC ;深圳仓 ;峰峰 ;15343351331 ;广东省东莞市凤岗镇浸校塘东良巷逸乐轩E栋5号楼 ;6 ;79 ;732 ;广东省 ;东莞市
//XDYYWC ;义乌仓 ;小田 ;19058117371 ;浙江省金华市义乌市北苑街道西站大道妈妈商贸18号库39号楼誉达 ;31 ;386 ;3409 ;浙江省 ;金华市 XDYYWC ;义乌仓 ;小田 ;19058117371 ;浙江省金华市义乌市北苑街道西站大道妈妈商贸18号库39号楼誉达 ;31 ;386 ;3409 ;浙江省 ;金华市";
//XDYJJC ;晋江仓 ;安群 ;19905951984 ;福建省泉州市南安市霞美镇温山村431号鸿鹄大厦 ;4 ;58 ;569 ;福建省 ;泉州市 //XDYJJC ;晋江仓 ;安群 ;19905951984 ;福建省泉州市南安市霞美镇温山村431号鸿鹄大厦 ;4 ;58 ;569 ;福建省 ;泉州市
//XDYCDC ;成都仓 ;谢春虹 ;15828201479 ;四川省资阳市乐至县仙鹤大道桑都街15-19号仓库(不要放驿站,送到仓库) ;26 ;340 ;2898 ;四川省 ;资阳市 //XDYCDC ;成都仓 ;谢春虹 ;15828201479 ;四川省资阳市乐至县仙鹤大道桑都街15-19号仓库(不要放驿站,送到仓库) ;26 ;340 ;2898 ;四川省 ;资阳市
//XDYCHONGQC ;重庆2仓 ;翁桂柱 ;18923911055 ;重庆市九龙坡区中梁山街道云飞九龙香山(二纵线东50米)重庆九龙坡区渝州公司 ;32 ;394 ;3339 //XDYCHONGQC ;重庆2仓 ;翁桂柱 ;18923911055 ;重庆市九龙坡区中梁山街道云飞九龙香山(二纵线东50米)重庆九龙坡区渝州公司 ;32 ;394 ;3339
+29 -6
View File
@@ -1,4 +1,5 @@
using AllBase.Model.Result; using AllBase.Model.MvvmBaseClasses;
using AllBase.Model.Result;
using NaiBa.Util; using NaiBa.Util;
using Newtonsoft.Json; using Newtonsoft.Json;
using NPOI.SS.Formula.Functions; using NPOI.SS.Formula.Functions;
@@ -32,14 +33,32 @@ namespace AllBase.Model.DBModel
public DateTime add_time { get; set; } public DateTime add_time { get; set; }
public DateTime mdy_time { get; set; } public DateTime mdy_time { get; set; }
} }
public class WXBuyMapSkusInfo public class WXBuyMapSkusInfo : PropertyNotifyObject
{ {
public bool? IsChecked
{
get { return this.GetValue(x => x.IsChecked); }
set { this.SetValue(x => x.IsChecked, value); }
}
public long id { get; set; } public long id { get; set; }
public string user_name { get; set; } public string user_name { get; set; }
public string spu_code { get; set; } public string spu_code { get; set; }
public string map_url { get; set; } public string map_url
public string map_goods_name { get; set; } {
public string map_goods_id { get; set; } get { return this.GetValue(x => x.map_url); }
set { this.SetValue(x => x.map_url, value); }
}
public string map_goods_name
{
get { return this.GetValue(x => x.map_goods_name); }
set { this.SetValue(x => x.map_goods_name, value); }
}
public string map_goods_id
{
get { return this.GetValue(x => x.map_goods_id); }
set { this.SetValue(x => x.map_goods_id, value); }
}
string _map_skus; string _map_skus;
public string map_skus public string map_skus
{ {
@@ -55,7 +74,11 @@ namespace AllBase.Model.DBModel
} }
} }
[JsonIgnore] [JsonIgnore]
public pddFrontGoods3Lite pdd_front_goods3_Lite { get; private set; } public pddFrontGoods3Lite pdd_front_goods3_Lite
{
get { return this.GetValue(x => x.pdd_front_goods3_Lite); }
set { this.SetValue(x => x.pdd_front_goods3_Lite, value); }
}
/// <summary> /// <summary>
/// 发货地(省,市) /// 发货地(省,市)
/// </summary> /// </summary>
@@ -10,12 +10,12 @@ namespace AllBase.Model.DBModel
{ {
public string OutOrderNumStr public string OutOrderNumStr
{ {
get { return "采购单号:" + out_order_no; } get { return out_order_no; }
set { } set { }
} }
public string OutOrderBuyerStr public string OutOrderBuyerStr
{ {
get { return "采购账户:" + buyer_account; } get { return buyer_account; }
set { } set { }
} }
@@ -37,11 +37,21 @@ namespace AllBase.Model.DBModel
{ {
get { return this.GetValue(x => x.BuyMap); } get { return this.GetValue(x => x.BuyMap); }
set { this.SetValue(x => x.BuyMap, value); } set { this.SetValue(x => x.BuyMap, value); }
}
public Visibility MapSkusBtnVisibility
{
get { return this.GetValue(x => x.MapSkusBtnVisibility); }
set { this.SetValue(x => x.MapSkusBtnVisibility, value); }
} }
public List<WXBuyMapSkusInfo> BuyMapSkus public List<WXBuyMapSkusInfo> BuyMapSkus
{ {
get { return this.GetValue(x => x.BuyMapSkus); } get { return this.GetValue(x => x.BuyMapSkus); }
set { this.SetValue(x => x.BuyMapSkus, value); } set
{
this.SetValue(x => x.BuyMapSkus, value);
if (value != null && value.Count > 0) MapSkusBtnVisibility = Visibility.Visible;
else MapSkusBtnVisibility = Visibility.Collapsed;
}
} }
/// <summary> /// <summary>
/// 采购按钮文字 /// 采购按钮文字
@@ -252,19 +262,19 @@ namespace AllBase.Model.DBModel
if (ItemTransitOrder?.pre_allocated_order_no != 1 && ItemTransitOrder?.pre_allocated_order_no != 3) if (ItemTransitOrder?.pre_allocated_order_no != 1 && ItemTransitOrder?.pre_allocated_order_no != 3)
this.TransitOrderWaybillToWareHouseStr = null; this.TransitOrderWaybillToWareHouseStr = null;
else else
this.TransitOrderWaybillToWareHouseStr = "买手物流:" + ItemTransitOrder.express_1_company + "-" + ItemTransitOrder.express_1_waybill; this.TransitOrderWaybillToWareHouseStr = ItemTransitOrder.express_1_company + "-" + ItemTransitOrder.express_1_waybill;
// 提前取号物流 // 提前取号物流
if (ItemTransitOrder?.pre_allocated_order_no != 2) if (ItemTransitOrder?.pre_allocated_order_no != 2)
this.TransitOrderWaybillFakeStr = null; this.TransitOrderWaybillFakeStr = null;
else else
this.TransitOrderWaybillFakeStr = "取号物流:" + ItemTransitOrder.express_1_company + "-" + ItemTransitOrder.express_1_waybill; this.TransitOrderWaybillFakeStr = ItemTransitOrder.express_1_company + "-" + ItemTransitOrder.express_1_waybill;
// 仓库下游物流 // 仓库下游物流
if (ItemTransitOrder == null || ItemTransitOrder.express_2_company.IsNullOrEmpty() || ItemTransitOrder.express_2_waybill.IsNullOrEmpty()) if (ItemTransitOrder == null || ItemTransitOrder.express_2_company.IsNullOrEmpty() || ItemTransitOrder.express_2_waybill.IsNullOrEmpty())
TransitOrderWaybillFromWareHouseStr = null; TransitOrderWaybillFromWareHouseStr = null;
else else
TransitOrderWaybillFromWareHouseStr = "仓库物流:" + ItemTransitOrder.express_2_company + "-" + ItemTransitOrder.express_2_waybill; TransitOrderWaybillFromWareHouseStr = ItemTransitOrder.express_2_company + "-" + ItemTransitOrder.express_2_waybill;
if (order_id == "3738461463336072960") if (order_id == "3738461463336072960")
{ {
@@ -712,7 +722,7 @@ namespace AllBase.Model.DBModel
if (ItemTransitOrderWithVoid == null) if (ItemTransitOrderWithVoid == null)
return ""; return "";
string timeStr = "采购时间:" + ItemTransitOrderWithVoid.created_time.ToString("yyyy-MM-dd HH:mm:ss"); string timeStr = ItemTransitOrderWithVoid.created_time.ToString("yyyy-MM-dd HH:mm:ss");
if (CreateDateTime.Date != ItemTransitOrderWithVoid.created_time.Date && ItemTransitOrderWithVoid.created_time > ItemTransitOrderWithVoid.created_time.Date.AddHours(1.5)) if (CreateDateTime.Date != ItemTransitOrderWithVoid.created_time.Date && ItemTransitOrderWithVoid.created_time > ItemTransitOrderWithVoid.created_time.Date.AddHours(1.5))
return timeStr + " ×"; return timeStr + " ×";
return timeStr + " √"; return timeStr + " √";
@@ -83,6 +83,7 @@ namespace AllBase.Model.DBModel
退货包裹扣费支出 = 26, 退货包裹扣费支出 = 26,
支付宝在线充值 = 30, 支付宝在线充值 = 30,
云仓退货支出 = 31, 云仓退货支出 = 31,
礼物单退费 = 34,
} }
/* /*
+34 -6
View File
@@ -1,4 +1,5 @@
using System; using AllBase.Model.MvvmBaseClasses;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -138,13 +139,17 @@ namespace AllBase.Model.Result
} }
public class pddFrontGoods3Lite public class pddFrontGoods3Lite : PropertyNotifyObject
{ {
public long? goodsId { get; set; } // 1661424397, public long? goodsId { get; set; } // 1661424397,
public string goodsName { get; set; } // "红薏仁5斤装 红薏仁米小薏米仁农家自产新红薏米1斤2斤苡仁糙薏米", public string goodsName { get; set; } // "红薏仁5斤装 红薏仁米小薏米仁农家自产新红薏米1斤2斤苡仁糙薏米",
public long? mallId { get; set; } // 525159017 public long? mallId { get; set; } // 525159017
public string mallName { get; set; } public string mallName { get; set; }
public List<frontSkuInfo3> skus { get; set; } public List<frontSkuInfo3> skus
{
get { return this.GetValue(x => x.skus); }
set { this.SetValue(x => x.skus, value); }
}
} }
public class newShareTitleInfo public class newShareTitleInfo
@@ -164,11 +169,20 @@ namespace AllBase.Model.Result
} }
public class frontSkuInfo3 public class frontSkuInfo3 : PropertyNotifyObject
{ {
public long? skuId { get; set; } // 28790184768, public long? skuId { get; set; } // 28790184768,
public long? goodsId { get; set; } // 1661424397, public long? goodsId { get; set; } // 1661424397,
public string thumbUrl { get; set; } // "https://t00img.yangkeduo.com/t10img/images/2018-06-09/5c7746a3608e75a2b65926f4ed0f34cb.jpeg", public string GoodsNameStr
{
get { return this.GetValue(x => x.GoodsNameStr); }
set { this.SetValue(x => x.GoodsNameStr, value); }
}
public string thumbUrl
{
get { return this.GetValue(x => x.thumbUrl); }
set { this.SetValue(x => x.thumbUrl, value); }
} // "https://t00img.yangkeduo.com/t10img/images/2018-06-09/5c7746a3608e75a2b65926f4ed0f34cb.jpeg",
public int? initQuantity { get; set; } // 0, public int? initQuantity { get; set; } // 0,
public int? quantity { get; set; } // 1000, public int? quantity { get; set; } // 1000,
public int? limitQuantity { get; set; } // 999999, public int? limitQuantity { get; set; } // 999999,
@@ -177,7 +191,21 @@ namespace AllBase.Model.Result
public int? defaultQuantity { get; set; } // 100, public int? defaultQuantity { get; set; } // 100,
public int? isOnsale { get; set; } // 1, public int? isOnsale { get; set; } // 1,
public string spec { get; set; } // "677094835", public string spec { get; set; } // "677094835",
public List<frontSpecInfo3> specs { get; set; } public string SpecNameStr
{
get { return this.GetValue(x => x.SpecNameStr) == null ? string.Join(",", specs?.Select(s => s.spec_value)) : this.GetValue(x => x.SpecNameStr); }
set { this.SetValue(x => x.SpecNameStr, value); }
}
List<frontSpecInfo3> _specs = new List<frontSpecInfo3>();
public List<frontSpecInfo3> specs
{
get => _specs;
set
{
_specs = value;
SpecNameStr = string.Join(",", value.Select(s => s.spec_value));
}
}
public int? price { get; set; } // 0, public int? price { get; set; } // 0,
public string normalPrice { get; set; } // "14.5", public string normalPrice { get; set; } // "14.5",
public string groupPrice { get; set; } // "13.5", public string groupPrice { get; set; } // "13.5",
+1 -1
View File
@@ -11,7 +11,7 @@
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Basic.xaml" /> <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Basic.xaml" />
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml" /> <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml" />
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml" /> <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml" />
<ResourceDictionary Source="Dictionary1.xaml" /> <ResourceDictionary Source="StyledDataGrid.xaml" />
<ResourceDictionary Source="Dictionary2.xaml" /> <ResourceDictionary Source="Dictionary2.xaml" />
</ResourceDictionary.MergedDictionaries> </ResourceDictionary.MergedDictionaries>
</ResourceDictionary> </ResourceDictionary>
+116 -1
View File
@@ -1,9 +1,14 @@
using System; using HandyControl.Controls;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Media;
namespace Main.Test; namespace Main.Test;
@@ -55,4 +60,114 @@ public class DataGridHelper
public static readonly DependencyProperty IsActiveProperty = public static readonly DependencyProperty IsActiveProperty =
DependencyProperty.RegisterAttached("IsActive", typeof(bool), typeof(DataGridHelper)); DependencyProperty.RegisterAttached("IsActive", typeof(bool), typeof(DataGridHelper));
public static DependencyProperty ShowRowNumberProperty = DependencyProperty.RegisterAttached("ShowRowNumber",
typeof(bool), typeof(DataGridHelper),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits, OnShowRowNumberChanged));
public static bool GetShowRowNumber(DependencyObject target) => (bool)target.GetValue(ShowRowNumberProperty);
public static void SetShowRowNumber(DependencyObject target, bool value)
{
target.SetValue(ShowRowNumberProperty, value);
}
private static void OnShowRowNumberChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
if (target is not DataGrid dataGrid) return;
var show = (bool)e.NewValue;
if (show)
{
dataGrid.LoadingRow += DataGrid_LoadingRow;
dataGrid.ItemContainerGenerator.ItemsChanged += ItemContainerGeneratorItemsChanged;
}
else
{
dataGrid.LoadingRow -= DataGrid_LoadingRow;
dataGrid.ItemContainerGenerator.ItemsChanged -= ItemContainerGeneratorItemsChanged;
}
void ItemContainerGeneratorItemsChanged(object sender, ItemsChangedEventArgs e)
{
var generator = dataGrid.ItemContainerGenerator;
var itemsCount = dataGrid.Items.Count;
if (show)
{
for (var i = 0; i < itemsCount; i++)
{
var row = (DataGridRow)generator.ContainerFromIndex(i);
if (row != null)
{
row.Header = (i + 1).ToString();
}
}
}
else
{
for (var i = 0; i < itemsCount; i++)
{
var row = (DataGridRow)generator.ContainerFromIndex(i);
if (row != null)
{
row.Header = null;
}
}
}
}
}
private static void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = (e.Row.GetIndex() + 1).ToString();
}
public static readonly DependencyProperty ShowBorderProperty =
DependencyProperty.RegisterAttached("ShowBorder", typeof(bool),
typeof(DataGridHelper), new PropertyMetadata(false, OnShowBorderChanged));
public static void SetShowBorder(DependencyObject element, bool value)
=> element.SetValue(ShowBorderProperty, value);
public static bool GetShowBorder(DependencyObject element)
=> (bool)element.GetValue(ShowBorderProperty);
private static void OnShowBorderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is DataGridColumnHeader header && (bool)e.NewValue)
{
header.Loaded += (s, args) =>
{
var layer = AdornerLayer.GetAdornerLayer(header);
if (layer != null)
{
layer.Add(new BorderAdorner(header));
}
};
}
}
}
public class BorderAdorner : Adorner
{
public BorderAdorner(UIElement adornedElement) : base(adornedElement) { }
protected override void OnRender(DrawingContext drawingContext)
{
var header = AdornedElement as DataGridColumnHeader;
if (header == null) return;
var pen = new Pen(header.BorderBrush ?? new SolidColorBrush(Colors.LightGray), 1);
// 绘制右侧竖线(永远不消失)
drawingContext.DrawLine(pen,
new Point(header.ActualWidth - 0.5, 0),
new Point(header.ActualWidth - 0.5, header.ActualHeight));
}
} }
+78
View File
@@ -0,0 +1,78 @@
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Prism.Mvvm;
namespace Main.Test;
public class ItemInfo : BindableBase
{
public int Code { get; init; }
public string Name { get; init; } = "";
public string Value => Price.ToString("N2", CultureInfo.CurrentCulture);
public decimal Price { get; init; }
public int Qty { get; init; }
public string Sku { get; init; } = "";
public string Shop { get; init; } = "";
public string Buyer { get; init; } = "";
public string Address { get; init; } = "";
public string Remark { get; init; } = "";
public DateTime CreatedAt { get; init; }
public ImageSource Thumbnail { get; init; } = null!;
public string? ThumbnailUrl { get; init; }
private string status = "待处理";
public string Status { get => status; set => SetProperty(ref status, value); }
}
internal static class DemoData
{
// 冻结并共享小尺寸位图,滚动不触发网络请求或重复解码。
private static readonly ImageSource[] Thumbnails = CreateThumbnails();
public static List<ItemInfo> Create(int count, int networkImageSize = 0)
{
string[] names = ["轻量通勤双肩包", "纯棉宽松短袖", "旅行收纳组合", "便携保温水杯", "无线办公鼠标", "桌面收纳置物盒", "运动休闲鞋", "折叠防晒遮阳伞"];
string[] shops = ["城市生活旗舰店", "优选数码专营店", "日常好物集合店", "远行户外用品店"];
var random = new Random(20261022);
var session = Guid.NewGuid().ToString("N");
var result = new List<ItemInfo>(count);
for (var i = 0; i < count; i++)
result.Add(new ItemInfo
{
Code = 100000 + i, Name = names[i % names.Length] + " · 秋季新品 / 品质款",
Price = random.Next(1900, 69900) / 100m, Qty = random.Next(1, 100),
Sku = $"SKU-{i:000000} / {(i % 2 == 0 ? "雾蓝" : "米白")} / 标准款",
Shop = shops[i % shops.Length], Buyer = $"买家{i:00000}",
Address = $"浙江省杭州市西湖区 文一路 {i % 300 + 1} 号 · 联系尾号 {i % 10000:0000}",
Remark = i % 3 == 0 ? "请核对规格,周末可收货;外包装请加固。" : "常规发货 / 已核对收货信息",
CreatedAt = new DateTime(2026, 10, 22, 12, 0, 0).AddMinutes(-i),
Status = new[] { "待处理", "已确认", "待发货", "已完成" }[i % 4],
Thumbnail = Thumbnails[i % Thumbnails.Length],
ThumbnailUrl = networkImageSize == 0 ? null : $"https://picsum.photos/seed/{session}-{i}/{networkImageSize}/{networkImageSize}"
});
return result;
}
private static ImageSource[] CreateThumbnails()
{
var images = new ImageSource[16];
for (var i = 0; i < images.Length; i++)
{
var visual = new DrawingVisual();
using (var dc = visual.RenderOpen())
{
var color = Color.FromRgb((byte)(55 + i * 11), (byte)(100 + i * 6), (byte)(165 - i * 4));
dc.DrawRoundedRectangle(new SolidColorBrush(Color.FromRgb(241, 245, 249)), null, new Rect(0, 0, 72, 72), 8, 8);
var brush = new SolidColorBrush(color);
var pen = new Pen(brush, 4);
dc.DrawRoundedRectangle(null, pen, new Rect(25, 12, 22, 24), 10, 10);
dc.DrawRoundedRectangle(brush, null, new Rect(14, 26, 44, 36), 6, 6);
dc.DrawLine(new Pen(Brushes.White, 2), new Point(24, 44), new Point(48, 44));
}
var bitmap = new RenderTargetBitmap(72, 72, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(visual); bitmap.Freeze(); images[i] = bitmap;
}
return images;
}
}
+255 -37
View File
@@ -6,52 +6,270 @@
xmlns:local="clr-namespace:Main.Test" xmlns:local="clr-namespace:Main.Test"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:tf="Trade.Framework" xmlns:tf="Trade.Framework"
xmlns:views="clr-namespace:Main.Test.Views"
xmlns:vm="clr-namespace:Main.Test.ViewModels" xmlns:vm="clr-namespace:Main.Test.ViewModels"
Title="MainWindow" Title="复杂表格 · 运行测试"
Width="800" Width="1380"
Height="450" Height="820"
MinWidth="900"
MinHeight="500"
DataContext="{tf:DISource Type=vm:MainViewModel}" DataContext="{tf:DISource Type=vm:MainViewModel}"
NonClientAreaContent=""
NonClientAreaHeight="200"
ResizeMode="CanResizeWithGrip"
WindowStartupLocation="CenterScreen" WindowStartupLocation="CenterScreen"
mc:Ignorable="d"> mc:Ignorable="d">
<tf:WindowBase.Resources>
<Grid Margin="0,0,0,0"> <Style x:Key="ActionButton" TargetType="Button">
<DataGrid <Setter Property="Padding" Value="9,4" />
Height="Auto" <Setter Property="Margin" Value="0,0,6,0" />
<Setter Property="MinWidth" Value="48" />
</Style>
<ContextMenu x:Key="OrderRowMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem
Command="{Binding PlacementTarget.Tag.DetailCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}"
Header="查看详情" />
<MenuItem
Command="{Binding PlacementTarget.Tag.ConfirmCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}"
Header="确认 / 撤销确认" />
<Separator />
<MenuItem
Command="{Binding PlacementTarget.Tag.CopyCodeCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}"
Header="复制编码" />
</ContextMenu>
</tf:WindowBase.Resources>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DockPanel Margin="0,0,0,12">
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
<ComboBox
x:Name="ImageMode"
Width="155"
Margin="0,0,8,0"
VerticalContentAlignment="Center"
SelectedIndex="0">
<ComboBoxItem Content="本地图片" Tag="0" />
<ComboBoxItem Content="Picsum 160px" Tag="160" />
<ComboBoxItem Content="Picsum 800px" Tag="800" />
</ComboBox>
<ComboBox
x:Name="DataSize"
Width="115"
Margin="0,0,8,0"
VerticalContentAlignment="Center"
SelectedIndex="1">
<ComboBoxItem Content="1,000 行" Tag="1000" />
<ComboBoxItem Content="10,000 行" Tag="10000" />
<ComboBoxItem Content="50,000 行" Tag="50000" />
</ComboBox>
<Button
x:Name="LoadButton"
Click="LoadData_Click"
Content="加载数据"
Style="{StaticResource ActionButton}" />
<Button
x:Name="ImageBenchmarkButton"
Click="ImageBenchmark_Click"
Content="图片滚动测试"
Style="{StaticResource ActionButton}" />
<Button
x:Name="BenchmarkButton"
Click="Benchmark_Click"
Content="运行性能测试"
Style="{StaticResource ActionButton}" />
</StackPanel>
<StackPanel>
<TextBlock
FontSize="20"
FontWeight="SemiBold"
Text="订单工作台 / 复杂内容测试" />
<StackPanel Margin="0,5,0,0" Orientation="Horizontal">
<TextBlock Foreground="#64748B" Text="{Binding Data.Count, StringFormat=共 {0:N0} 行}" />
<TextBlock
Margin="12,0,0,0"
Foreground="#64748B"
Text="{Binding SelectedCount, StringFormat=已选 {0:N0} 行}" />
</StackPanel>
</StackPanel>
</DockPanel>
<local:StyledDataGrid
x:Name="OrdersGrid"
Grid.Row="1"
d:ItemsSource="{d:SampleData ItemCount=10}" d:ItemsSource="{d:SampleData ItemCount=10}"
GridLinesVisibility="Horizontal"
IsReadOnly="True"
ItemsSource="{Binding Data}" ItemsSource="{Binding Data}"
Style="{StaticResource DefaultDataGridStyle}"> RowContextMenu="{StaticResource OrderRowMenu}"
<DataGrid.Columns> RowDetailsVisibilityMode="Collapsed"
RowHeight="92"
SelectRowOnRightClick="True"
SelectedItems="{Binding SelectedItems, Mode=TwoWay}"
SelectionMode="Extended"
ShowCheckBox="True"
ShowRowNumber="True"
ShowSelectAll="True">
<local:StyledDataGrid.Columns>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="90"
MinWidth="100" Binding="{Binding Code}"
Binding="{Binding Code, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="编码" />
Header="编码" <DataGridTemplateColumn
IsReadOnly="True" /> Width="300"
Header="商品 / 规格"
SortMemberPath="Name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid Margin="0,7">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="68" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border
Width="58"
Height="58"
Background="#F1F5F9"
CornerRadius="6">
<local:NetworkThumbnail
Width="58"
Height="58"
Placeholder="{Binding Thumbnail}"
Stretch="Uniform"
Url="{Binding ThumbnailUrl}" />
</Border>
<StackPanel Grid.Column="1" VerticalAlignment="Center">
<TextBlock
FontWeight="SemiBold"
Text="{Binding Name}"
TextTrimming="CharacterEllipsis"
ToolTip="{Binding Name}" />
<TextBlock
Margin="0,5,0,0"
FontSize="11"
Opacity="0.65"
Text="{Binding Sku}" />
<TextBlock
Margin="0,4,0,0"
FontSize="11"
Opacity="0.65"
Text="{Binding Shop}" />
</StackPanel>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="90"
MinWidth="100" Binding="{Binding Price, StringFormat=N2}"
Binding="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CellStyle="{DynamicResource StyledNumberCellStyle}"
Header="名称" Header="单价 / 元"
IsReadOnly="True" /> HeaderStyle="{DynamicResource DefaultNumberCellHeaderStyle}" />
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="65"
MinWidth="100" Binding="{Binding Qty}"
Binding="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CellStyle="{DynamicResource StyledNumberCellStyle}"
Header="值" Header="数量"
IsReadOnly="True" /> HeaderStyle="{DynamicResource DefaultNumberCellHeaderStyle}" />
<DataGridTemplateColumn
Width="230"
Header="买家 / 收货信息"
SortMemberPath="Buyer">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Center">
<TextBlock FontWeight="SemiBold" Text="{Binding Buyer}" />
<TextBlock
Margin="0,6,0,0"
FontSize="11"
Opacity="0.7"
Text="{Binding Address}"
TextWrapping="Wrap" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn
Width="95"
Header="状态"
SortMemberPath="Status">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Border
Padding="8,4"
HorizontalAlignment="Left"
Background="#E8F4FF"
CornerRadius="4">
<TextBlock
FontSize="12"
Foreground="#1769AA"
Text="{Binding Status}" />
</Border>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="105"
MinWidth="100" Binding="{Binding CreatedAt, StringFormat=MM-dd HH:mm}"
Binding="{Binding Qty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="创建时间" />
CellStyle="{DynamicResource DefaultNumberCellStyle}" <DataGridTemplateColumn
Header="数字" Width="165"
HeaderStyle="{DynamicResource DefaultNumberCellHeaderStyle}" Header="备注"
IsReadOnly="True" /> SortMemberPath="Remark">
</DataGrid.Columns> <DataGridTemplateColumn.CellTemplate>
</DataGrid> <DataTemplate>
<TextBlock
MaxHeight="60"
VerticalAlignment="Center"
Text="{Binding Remark}"
TextWrapping="Wrap" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Width="145" Header="操作">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Center" Orientation="Horizontal">
<Button
Command="{Binding DataContext.DetailCommand, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}"
CommandParameter="{Binding}"
Content="详情"
Style="{StaticResource ActionButton}" />
<Button
Command="{Binding DataContext.ConfirmCommand, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}"
CommandParameter="{Binding}"
Content="确认"
Style="{StaticResource ActionButton}" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</local:StyledDataGrid.Columns>
</local:StyledDataGrid>
<TextBlock
Grid.Row="2"
Margin="0,10,0,6"
Text="{Binding ActionMessage}"
TextWrapping="Wrap" />
<Border
Grid.Row="3"
Padding="10,8"
Background="#F1F5F9"
CornerRadius="5">
<StackPanel>
<TextBlock
x:Name="ImageStatisticsText"
Margin="0,0,0,4"
Foreground="#475569"
TextWrapping="Wrap" />
<TextBlock
x:Name="PerformanceText"
Foreground="#475569"
Text="选择数据量后运行性能测试:连续滚动 60 次,并测量全选、取消全选及已生成行数。"
TextWrapping="Wrap" />
</StackPanel>
</Border>
</Grid> </Grid>
</tf:WindowBase> </tf:WindowBase>
+136 -18
View File
@@ -1,35 +1,153 @@
using Bogus; using System.Diagnostics;
using System.Text;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Media.Imaging; using System.Windows.Threading;
using System.Windows.Navigation; using Main.Test.ViewModels;
using System.Windows.Shapes;
using Trade.Framework.Controls; using Trade.Framework.Controls;
namespace Main.Test; namespace Main.Test;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : WindowBase public partial class MainWindow : WindowBase
{ {
public MainWindow() public MainWindow()
{ {
InitializeComponent(); InitializeComponent();
var mainHeaderImageContent = new MainHeaderImageContent(); var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
NonClientAreaHeight = mainHeaderImageContent.Height; timer.Tick += (_, _) => ImageStatisticsText.Text = ThumbnailLoader.Statistics;
NonClientAreaContent = mainHeaderImageContent; Loaded += (_, _) => timer.Start();
Closed += (_, _) => timer.Stop();
}
private async void LoadData_Click(object sender, RoutedEventArgs e)
{
SetBusy(true);
try
{
var count = int.Parse((string)((ComboBoxItem)DataSize.SelectedItem).Tag);
var watch = Stopwatch.StartNew();
var vm = (MainViewModel)DataContext;
vm.NetworkImageSize = int.Parse((string)((ComboBoxItem)ImageMode.SelectedItem).Tag);
await vm.LoadAsync(count);
OrdersGrid.ScrollIntoView(OrdersGrid.Items[0]);
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
PerformanceText.Text = $"加载 {count:N0} 行(含生成与首次布局):{watch.Elapsed.TotalMilliseconds:N0} ms。可继续测试滚动和全选。";
}
catch (Exception ex) { PerformanceText.Text = $"加载失败:{ex.Message}"; }
finally { SetBusy(false); }
}
private async void Benchmark_Click(object sender, RoutedEventArgs e)
{
SetBusy(true);
try { PerformanceText.Text = await RunPerformanceTestAsync(); }
catch (Exception ex) { PerformanceText.Text = $"测试失败:{ex.Message}"; }
finally { SetBusy(false); }
}
private async void ImageBenchmark_Click(object sender, RoutedEventArgs e)
{
SetBusy(true);
try { PerformanceText.Text = await RunImagePerformanceTestAsync(); }
catch (Exception ex) { PerformanceText.Text = $"图片测试失败:{ex.Message}"; }
finally { SetBusy(false); }
}
public async Task<string> RunImagePerformanceTestAsync()
{
if (OrdersGrid.Items.Count == 0 || ((MainViewModel)DataContext).NetworkImageSize == 0)
return "请先选择 Picsum 图片模式并点击加载数据,再运行图片滚动测试。";
var viewer = FindVisual<ScrollViewer>(OrdersGrid).First();
var offset = viewer.VerticalOffset;
var samples = new[] { new List<double>(), new List<double>() };
var heartbeat = Stopwatch.StartNew();
var lastTick = heartbeat.Elapsed.TotalMilliseconds;
var maxDelay = 0d;
var pulse = new DispatcherTimer(DispatcherPriority.Normal) { Interval = TimeSpan.FromMilliseconds(50) };
pulse.Tick += (_, _) =>
{
var now = heartbeat.Elapsed.TotalMilliseconds;
maxDelay = Math.Max(maxDelay, Math.Max(0, now - lastTick - 50));
lastTick = now;
};
pulse.Start();
try
{
viewer.ScrollToHorizontalOffset(0);
for (var pass = 0; pass < 2; pass++)
{
PerformanceText.Text = pass == 0 ? "首次滚动:网络图片正在加载…" : "重复访问相同位置:比较缓存与重新加载…";
for (var i = 0; i < 40; i++)
{
var watch = Stopwatch.StartNew();
viewer.ScrollToVerticalOffset(i % 24);
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
samples[pass].Add(watch.Elapsed.TotalMilliseconds);
await Task.Delay(150);
}
}
// 有界等待当前可见图片,避免把尚未完成的请求当作加载成功。
var wait = Stopwatch.StartNew();
while (ThumbnailLoader.Pending > 0 && wait.Elapsed < TimeSpan.FromSeconds(8)) await Task.Delay(100);
var first = samples[0].Order().ToArray(); var revisit = samples[1].Order().ToArray();
return $"Picsum {((MainViewModel)DataContext).NetworkImageSize}px / {OrdersGrid.Items.Count:N0} 行 | 首次滚动均值 {first.Average():N1} ms / P95 {first[37]:N1} ms | 复访均值 {revisit.Average():N1} ms / P95 {revisit[37]:N1} ms | UI 心跳最大延迟 {maxDelay:N1} ms(非帧率);图片统计为本次进程累计,取消表示滚出视口。";
}
finally { pulse.Stop(); viewer.ScrollToVerticalOffset(offset); }
}
// 测量 UI 线程滚动与布局响应,不等同于 GPU 帧率。
public async Task<string> RunPerformanceTestAsync()
{
if (OrdersGrid.Items.Count == 0) return "没有可测试的数据。";
var viewer = FindVisual<ScrollViewer>(OrdersGrid).First();
var offset = viewer.VerticalOffset;
var selected = ((DataGrid)OrdersGrid).SelectedItems.Cast<object>().ToArray();
var samples = new List<double>();
try
{
OrdersGrid.UnselectAll();
OrdersGrid.ScrollIntoView(OrdersGrid.Items[0]);
viewer.ScrollToHorizontalOffset(0);
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
for (var i = 0; i < 60; i++)
{
var watch = Stopwatch.StartNew();
viewer.ScrollToVerticalOffset(viewer.ScrollableHeight * ((i * 17) % 60) / 59d);
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
samples.Add(watch.Elapsed.TotalMilliseconds);
}
var selectWatch = Stopwatch.StartNew();
OrdersGrid.SelectAll();
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
var selectMs = selectWatch.Elapsed.TotalMilliseconds;
selectWatch.Restart(); OrdersGrid.UnselectAll();
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
var clearMs = selectWatch.Elapsed.TotalMilliseconds;
var realized = FindVisual<DataGridRow>(OrdersGrid).Count();
samples.Sort();
return $"{OrdersGrid.Items.Count:N0} 行 / 9 列 | 滚动与布局:均值 {samples.Average():N1} ms,P95 {samples[56]:N1} ms,最大 {samples[^1]:N1} ms | 全选 {selectMs:N0} ms / 取消 {clearMs:N0} ms | 已生成行 {realized} | 进程内存 {Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024} MB(不等同帧率)";
}
finally
{
OrdersGrid.RestoreSelection(selected);
viewer.ScrollToVerticalOffset(offset);
} }
} }
public class ItemInfo private void SetBusy(bool busy)
{ {
public int Code { get; set; } LoadButton.IsEnabled = BenchmarkButton.IsEnabled = ImageBenchmarkButton.IsEnabled = DataSize.IsEnabled = ImageMode.IsEnabled = !busy;
public string Name { get; set; } OrdersGrid.IsEnabled = !busy;
public string Value { get; set; } }
public int Qty { get; set; }
private static IEnumerable<T> FindVisual<T>(DependencyObject parent) where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T match) yield return match;
foreach (var descendant in FindVisual<T>(child)) yield return descendant;
}
}
} }
+100
View File
@@ -0,0 +1,100 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Threading;
namespace Main.Test;
public partial class StyledDataGrid
{
private DispatcherTimer? imageResumeTimer;
private bool draggingScrollThumb;
private void InitializeImageLoadingPause()
{
imageResumeTimer = new DispatcherTimer(DispatcherPriority.Background, Dispatcher)
{
Interval = TimeSpan.FromMilliseconds(500)
};
imageResumeTimer.Tick += (_, _) =>
{
imageResumeTimer.Stop();
if (!draggingScrollThumb && IsLoaded) SetImageLoadingSuspended(false);
};
AddHandler(Thumb.DragStartedEvent, new DragStartedEventHandler(ScrollThumbDragStarted), true);
AddHandler(Thumb.DragCompletedEvent, new DragCompletedEventHandler(ScrollThumbDragCompleted), true);
AddHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(ImageScrollChanged), true);
Unloaded += (_, _) =>
{
imageResumeTimer.Stop(); draggingScrollThumb = false;
SetImageLoadingSuspended(true);
};
Loaded += (_, _) => { ApplyImageLoadingOptions(); SetImageLoadingSuspended(false); };
ApplyImageLoadingOptions();
}
private void SetImageLoadingSuspended(bool suspended)
{
SetValue(IsImageLoadingSuspendedPropertyKey, suspended);
NetworkThumbnail.SetIsLoadingSuspended(this, suspended);
}
private void ApplyImageLoadingOptions()
{
NetworkThumbnail.SetCacheEnabled(this, EnableImageCache);
if (imageResumeTimer == null) return;
if (!PauseImageLoadingWhileDragging)
{
imageResumeTimer.Stop(); draggingScrollThumb = false; SetImageLoadingSuspended(false);
}
}
private bool IsOwnScrollBar(DependencyObject? source)
{
var foundScrollBar = false;
for (var parent = source; parent != null; parent = VisualTreeHelper.GetParent(parent))
{
if (parent is ScrollBar) foundScrollBar = true;
if (parent is DataGrid) return ReferenceEquals(parent, this) && foundScrollBar;
}
return false;
}
private void ScrollThumbDragStarted(object sender, DragStartedEventArgs e)
{
if (!PauseImageLoadingWhileDragging || !IsOwnScrollBar(e.OriginalSource as DependencyObject)) return;
draggingScrollThumb = true;
imageResumeTimer!.Stop();
// 继承到可见图片及随后回收生成的新行,立即取消请求并清空图片。
SetImageLoadingSuspended(true);
}
private void ScrollThumbDragCompleted(object sender, DragCompletedEventArgs e)
{
if (!PauseImageLoadingWhileDragging || !IsOwnScrollBar(e.OriginalSource as DependencyObject)) return;
draggingScrollThumb = false;
RestartImageResumeTimer();
}
private void ImageScrollChanged(object sender, ScrollChangedEventArgs e)
{
if (!NetworkThumbnail.GetIsLoadingSuspended(this) || draggingScrollThumb ||
(e.VerticalChange == 0 && e.HorizontalChange == 0) ||
!IsOwnScrollViewer(e.OriginalSource as DependencyObject)) return;
RestartImageResumeTimer();
}
private bool IsOwnScrollViewer(DependencyObject? source)
{
for (var parent = source; parent != null; parent = VisualTreeHelper.GetParent(parent))
if (parent is DataGrid) return ReferenceEquals(parent, this);
return false;
}
private void RestartImageResumeTimer()
{
imageResumeTimer!.Stop();
imageResumeTimer.Start();
}
}
+51
View File
@@ -0,0 +1,51 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Main.Test;
public partial class StyledDataGrid
{
public static readonly DependencyProperty NoDataTipsProperty = DataGridHelper.NoDataTipsProperty.AddOwner(typeof(StyledDataGrid));
public string NoDataTips { get => (string)GetValue(NoDataTipsProperty); set => SetValue(NoDataTipsProperty, value); }
public static readonly DependencyProperty IsActiveProperty = DataGridHelper.IsActiveProperty.AddOwner(typeof(StyledDataGrid));
/// <summary>为 true 时抑制空数据提示;可在业务加载数据期间设置。</summary>
public bool IsActive { get => (bool)GetValue(IsActiveProperty); set => SetValue(IsActiveProperty, value); }
public static readonly DependencyProperty RowContextMenuProperty = DependencyProperty.Register(nameof(RowContextMenu), typeof(ContextMenu), typeof(StyledDataGrid), new PropertyMetadata(null));
public ContextMenu? RowContextMenu { get => (ContextMenu?)GetValue(RowContextMenuProperty); set => SetValue(RowContextMenuProperty, value); }
public static readonly DependencyProperty ShowSelectAllProperty = DependencyProperty.Register(nameof(ShowSelectAll), typeof(bool), typeof(StyledDataGrid), new PropertyMetadata(true));
public static readonly DependencyProperty ToggleSelectionOnRowHeaderClickProperty = DependencyProperty.Register(nameof(ToggleSelectionOnRowHeaderClick), typeof(bool), typeof(StyledDataGrid), new PropertyMetadata(true));
public static readonly DependencyProperty SelectRowOnRightClickProperty = DependencyProperty.Register(nameof(SelectRowOnRightClick), typeof(bool), typeof(StyledDataGrid), new PropertyMetadata(false));
public static readonly DependencyProperty PauseImageLoadingWhileDraggingProperty = DependencyProperty.Register(nameof(PauseImageLoadingWhileDragging), typeof(bool), typeof(StyledDataGrid), new PropertyMetadata(true, ImageOptionsChanged));
public static readonly DependencyProperty EnableImageCacheProperty = DependencyProperty.Register(nameof(EnableImageCache), typeof(bool), typeof(StyledDataGrid), new PropertyMetadata(true, ImageOptionsChanged));
private static readonly DependencyPropertyKey IsImageLoadingSuspendedPropertyKey = DependencyProperty.RegisterReadOnly(nameof(IsImageLoadingSuspended), typeof(bool), typeof(StyledDataGrid), new PropertyMetadata(false));
public static readonly DependencyProperty IsImageLoadingSuspendedProperty = IsImageLoadingSuspendedPropertyKey.DependencyProperty;
public bool ShowSelectAll { get => (bool)GetValue(ShowSelectAllProperty); set => SetValue(ShowSelectAllProperty, value); }
public bool ToggleSelectionOnRowHeaderClick { get => (bool)GetValue(ToggleSelectionOnRowHeaderClickProperty); set => SetValue(ToggleSelectionOnRowHeaderClickProperty, value); }
public bool SelectRowOnRightClick { get => (bool)GetValue(SelectRowOnRightClickProperty); set => SetValue(SelectRowOnRightClickProperty, value); }
/// <summary>默认开启;拖动时暂停并清空图片,停止滚动 500ms 后恢复。</summary>
public bool PauseImageLoadingWhileDragging { get => (bool)GetValue(PauseImageLoadingWhileDraggingProperty); set => SetValue(PauseImageLoadingWhileDraggingProperty, value); }
/// <summary>默认开启图片缓存;设为 false 时不读取或写入缓存。</summary>
public bool EnableImageCache { get => (bool)GetValue(EnableImageCacheProperty); set => SetValue(EnableImageCacheProperty, value); }
public bool IsImageLoadingSuspended => (bool)GetValue(IsImageLoadingSuspendedProperty);
private static void ImageOptionsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
=> ((StyledDataGrid)d).ApplyImageLoadingOptions();
protected override void OnPreviewMouseRightButtonDown(MouseButtonEventArgs e)
{
if (SelectRowOnRightClick && !e.Handled && SelectionUnit != DataGridSelectionUnit.Cell && e.OriginalSource is DependencyObject source)
{
var row = FindRow(source);
if (row != null && ItemsControl.ItemsControlFromItemContainer(row) == this && !row.IsSelected &&
row.Item != System.Windows.Data.CollectionView.NewItemPlaceholder)
{
UnselectAll(); row.SetCurrentValue(DataGridRow.IsSelectedProperty, true);
}
}
base.OnPreviewMouseRightButtonDown(e);
}
}
+279
View File
@@ -0,0 +1,279 @@
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace Main.Test;
/// <summary>带默认样式、行号和行选择勾选框的 DataGrid。</summary>
public partial class StyledDataGrid : DataGrid
{
public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register(
nameof(SelectedItems), typeof(IList), typeof(StyledDataGrid),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemsChanged));
/// <summary>可绑定的选中集合。使用 ObservableCollection 可从 VM 增删选中项;未绑定时返回原生选中集合。</summary>
public new IList SelectedItems
{
get => (IList?)GetValue(SelectedItemsProperty) ?? base.SelectedItems;
set => SetValue(SelectedItemsProperty, value);
}
/// <summary>批量恢复性能测试前的选择,只发出一次选择变更。</summary>
internal void RestoreSelection(IEnumerable<object> selected)
{
var available = Items.Cast<object>().ToHashSet();
BeginUpdateSelectedItems();
try
{
base.SelectedItems.Clear();
foreach (var item in selected)
if (available.Contains(item)) base.SelectedItems.Add(item);
}
finally { EndUpdateSelectedItems(); }
}
private bool synchronizingSelection;
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var grid = (StyledDataGrid)d;
if (e.NewValue is IList { IsReadOnly: true } or IList { IsFixedSize: true })
throw new ArgumentException("SelectedItems 必须绑定到可增删的集合,例如 ObservableCollection<T>。");
if (e.OldValue is INotifyCollectionChanged oldCollection)
CollectionChangedEventManager.RemoveHandler(oldCollection, grid.OnBoundSelectionChanged);
if (e.NewValue is INotifyCollectionChanged newCollection)
CollectionChangedEventManager.AddHandler(newCollection, grid.OnBoundSelectionChanged);
grid.ApplyBoundSelection();
}
private void OnBoundSelectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => ApplyBoundSelection();
private void ApplyBoundSelection()
{
if (synchronizingSelection || GetValue(SelectedItemsProperty) is not IList boundItems ||
ReferenceEquals(boundItems, base.SelectedItems) || SelectionUnit == DataGridSelectionUnit.Cell) return;
var available = Items.Cast<object>().ToHashSet();
var desired = boundItems.Cast<object>().Where(item => available.Contains(item) &&
item != System.Windows.Data.CollectionView.NewItemPlaceholder).Distinct().ToList();
if (SelectionMode == DataGridSelectionMode.Single) desired = desired.Take(1).ToList();
synchronizingSelection = true;
try
{
var desiredSet = desired.ToHashSet();
var current = base.SelectedItems.Cast<object>().ToHashSet();
if (SelectionMode == DataGridSelectionMode.Single)
SetCurrentValue(SelectedItemProperty, desired.FirstOrDefault());
else if (desired.Count == 0) UnselectAll();
else
{
foreach (var item in current)
if (!desiredSet.Contains(item)) base.SelectedItems.Remove(item);
foreach (var item in desired)
if (!current.Contains(item)) base.SelectedItems.Add(item);
}
}
finally { synchronizingSelection = false; }
UpdateSelectAllState();
}
private void PublishSelection()
{
if (synchronizingSelection || GetValue(SelectedItemsProperty) is not IList boundItems ||
ReferenceEquals(boundItems, base.SelectedItems)) return;
synchronizingSelection = true;
try
{
var current = base.SelectedItems.Cast<object>().ToArray();
if (current.Length == 0) boundItems.Clear();
else
{
var currentSet = current.ToHashSet();
for (var i = boundItems.Count - 1; i >= 0; i--)
if (!currentSet.Contains(boundItems[i]!)) boundItems.RemoveAt(i);
var boundSet = boundItems.Cast<object>().ToHashSet();
foreach (var item in current)
if (boundSet.Add(item)) boundItems.Add(item);
}
}
finally { synchronizingSelection = false; }
}
protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
var wasSynchronizing = synchronizingSelection;
synchronizingSelection = true;
try { base.OnItemsSourceChanged(oldValue, newValue); }
finally { synchronizingSelection = wasSynchronizing; }
ApplyBoundSelection();
}
private static readonly DependencyPropertyKey IsSelectionModeActivePropertyKey = DependencyProperty.RegisterReadOnly(
nameof(IsSelectionModeActive), typeof(bool), typeof(StyledDataGrid), new PropertyMetadata(false));
public static readonly DependencyProperty IsSelectionModeActiveProperty = IsSelectionModeActivePropertyKey.DependencyProperty;
/// <summary>点击行头勾选框后进入批量选择,取消所有选中后退出。</summary>
public bool IsSelectionModeActive => (bool)GetValue(IsSelectionModeActiveProperty);
public static readonly RoutedUICommand ToggleSelectAllCommand = new("全选或取消全选", nameof(ToggleSelectAllCommand), typeof(StyledDataGrid));
private static readonly DependencyPropertyKey AreAllRowsSelectedPropertyKey = DependencyProperty.RegisterReadOnly(
nameof(AreAllRowsSelected), typeof(bool?), typeof(StyledDataGrid), new PropertyMetadata(false));
public static readonly DependencyProperty AreAllRowsSelectedProperty = AreAllRowsSelectedPropertyKey.DependencyProperty;
/// <summary>全部选中为 true,部分选中为 null,未选中为 false。</summary>
public bool? AreAllRowsSelected => (bool?)GetValue(AreAllRowsSelectedProperty);
public static readonly DependencyProperty SelectedRowBackgroundProperty = DependencyProperty.Register(
nameof(SelectedRowBackground), typeof(Brush), typeof(StyledDataGrid),
new PropertyMetadata(new SolidColorBrush(Color.FromRgb(75, 178, 255))));
public static readonly DependencyProperty SelectedRowForegroundProperty = DependencyProperty.Register(
nameof(SelectedRowForeground), typeof(Brush), typeof(StyledDataGrid), new PropertyMetadata(Brushes.White));
public static readonly DependencyProperty ShowCheckBoxProperty = DependencyProperty.Register(
nameof(ShowCheckBox), typeof(bool), typeof(StyledDataGrid), new PropertyMetadata(false, HeaderOptionsChanged));
public static readonly DependencyProperty ShowRowNumberProperty = DependencyProperty.Register(
nameof(ShowRowNumber), typeof(bool), typeof(StyledDataGrid), new PropertyMetadata(false, HeaderOptionsChanged));
public Brush SelectedRowBackground { get => (Brush)GetValue(SelectedRowBackgroundProperty); set => SetValue(SelectedRowBackgroundProperty, value); }
public Brush SelectedRowForeground { get => (Brush)GetValue(SelectedRowForegroundProperty); set => SetValue(SelectedRowForegroundProperty, value); }
/// <summary>勾选状态与行 IsSelected 同步,可通过 SelectedItems 获取。</summary>
public bool ShowCheckBox { get => (bool)GetValue(ShowCheckBoxProperty); set => SetValue(ShowCheckBoxProperty, value); }
public bool ShowRowNumber { get => (bool)GetValue(ShowRowNumberProperty); set => SetValue(ShowRowNumberProperty, value); }
static StyledDataGrid()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(StyledDataGrid), new FrameworkPropertyMetadata(typeof(StyledDataGrid)));
}
public StyledDataGrid()
{
InitializeImageLoadingPause();
CommandBindings.Add(new CommandBinding(ToggleSelectAllCommand, (_, e) =>
{
if (AreAllRowsSelected == true) UnselectAll();
else
{
SelectAll();
SetValue(IsSelectionModeActivePropertyKey, base.SelectedItems.Count > 0);
}
e.Handled = true;
}, (_, e) =>
{
e.CanExecute = SelectionMode == DataGridSelectionMode.Extended &&
SelectionUnit != DataGridSelectionUnit.Cell && SelectableItemCount > 0;
e.Handled = true;
}));
AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(OnRowCheckBoxClick), true);
LoadingRow += (_, e) => UpdateRowNumber(e.Row);
ItemContainerGenerator.ItemsChanged += (_, _) => QueueHeaderUpdate();
Loaded += (_, _) => { ApplyBoundSelection(); QueueHeaderUpdate(); };
}
private void OnRowCheckBoxClick(object sender, RoutedEventArgs e)
{
if (e.OriginalSource is not CheckBox checkBox) return;
DependencyObject? parent = checkBox;
while (parent != null && parent != this)
{
if (parent is DataGridRowHeader header &&
ItemsControl.ItemsControlFromItemContainer(FindRow(header)) == this)
{
SetValue(IsSelectionModeActivePropertyKey, base.SelectedItems.Count > 0);
return;
}
parent = VisualTreeHelper.GetParent(parent);
}
}
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (!e.Handled && ShowCheckBox && ToggleSelectionOnRowHeaderClick && SelectionUnit != DataGridSelectionUnit.Cell)
{
for (var source = e.OriginalSource as DependencyObject; source != null && source != this;
source = source is FrameworkContentElement content ? content.Parent : VisualTreeHelper.GetParent(source))
{
// 保留行高拖动和嵌套表格自己的鼠标处理。
if (source is Thumb || source is DataGrid) break;
if (source is not DataGridRowHeader header) continue;
var row = FindRow(header);
if (row == null || ItemsControl.ItemsControlFromItemContainer(row) != this ||
row.Item == System.Windows.Data.CollectionView.NewItemPlaceholder) break;
// 在 DataGridRowHeader 默认单选逻辑之前处理整个行头,
// 包括勾选框四周的留白;阻止 CheckBox 再次切换造成双重反转。
e.Handled = true;
row.SetCurrentValue(DataGridRow.IsSelectedProperty, !row.IsSelected);
SetValue(IsSelectionModeActivePropertyKey, base.SelectedItems.Count > 0);
return;
}
}
base.OnPreviewMouseLeftButtonDown(e);
}
private static DataGridRow? FindRow(DependencyObject element)
{
for (DependencyObject? parent = element; parent != null; parent = parent is FrameworkContentElement content ? content.Parent : VisualTreeHelper.GetParent(parent))
if (parent is DataGridRow row) return row;
return null;
}
private static void HeaderOptionsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
=> ((StyledDataGrid)d).QueueHeaderUpdate();
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
{
base.OnItemsChanged(e);
QueueHeaderUpdate();
UpdateSelectAllState();
}
private int SelectableItemCount => Items.Count - (Items.Contains(System.Windows.Data.CollectionView.NewItemPlaceholder) ? 1 : 0);
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
PublishSelection();
base.OnSelectionChanged(e);
UpdateSelectAllState();
}
private void UpdateSelectAllState()
{
SetValue(AreAllRowsSelectedPropertyKey, base.SelectedItems.Count == 0 ? false :
base.SelectedItems.Count == SelectableItemCount ? true : (bool?)null);
if (base.SelectedItems.Count == 0) SetValue(IsSelectionModeActivePropertyKey, false);
CommandManager.InvalidateRequerySuggested();
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property == FontSizeProperty || e.Property == FontFamilyProperty ||
e.Property == FontStyleProperty || e.Property == FontWeightProperty || e.Property == FontStretchProperty)
QueueHeaderUpdate();
}
private bool headerUpdatePending;
private void QueueHeaderUpdate()
{
if (headerUpdatePending) return;
headerUpdatePending = true;
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
{
headerUpdatePending = false;
foreach (var row in GetRealizedRows(this)) UpdateRowNumber(row);
}));
}
private void UpdateRowNumber(DataGridRow row)
=> row.SetCurrentValue(DataGridRow.HeaderProperty, ShowRowNumber ? (row.GetIndex() + 1).ToString(CultureInfo.CurrentCulture) : null);
private IEnumerable<DataGridRow> GetRealizedRows(DependencyObject parent)
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is DataGridRow row && ItemsControl.ItemsControlFromItemContainer(row) == this) yield return row;
else if (child is not DataGrid)
foreach (var descendant in GetRealizedRows(child)) yield return descendant;
}
}
}
@@ -1,20 +1,19 @@
<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:Main.Test"
xmlns:ext="clr-namespace:Main.Test" xmlns:ext="clr-namespace:Main.Test"
xmlns:sys="clr-namespace:System;assembly=mscorlib"> xmlns:sys="clr-namespace:System;assembly=mscorlib">
<!--<FontFamily x:Key="FontFamily">Microsoft YaHei</FontFamily>
-->
<!-- 默认字体大小 -->
<!--
<sys:Double x:Key="DefaultFontSize">14</sys:Double>-->
<Style x:Key="DefaultCellHeaderStyle" TargetType="DataGridColumnHeader"> <Style x:Key="DefaultCellHeaderStyle" TargetType="DataGridColumnHeader">
<Setter Property="UseLayoutRounding" Value="True" />
<!--<Setter Property="ext:DataGridHelper.ShowBorder" Value="True" />-->
<Setter Property="Height" Value="{Binding ColumnHeaderHeight, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" /> <Setter Property="Height" Value="{Binding ColumnHeaderHeight, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
<Setter Property="Background" Value="#eeeeee" /> <Setter Property="Background" Value="#eeeeee" />
<Setter Property="BorderThickness" Value="1,0,1,1" /> <Setter Property="BorderThickness" Value="0,0,0,1" />
<Setter Property="Margin" Value="-1,0,0,0" /> <!-- 只保留底边框,竖线不再用 Border 画 -->
<Setter Property="HorizontalContentAlignment" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=HorizontalContentAlignment}" /> <Setter Property="HorizontalContentAlignment" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=HorizontalContentAlignment}" />
<Setter Property="Padding" Value="8,0" /> <Setter Property="Padding" Value="8,0" />
<Setter Property="FontSize" Value="{DynamicResource DefaultFontSize}" /> <Setter Property="FontSize" Value="{DynamicResource DefaultFontSize}" />
@@ -28,9 +27,15 @@
Padding="{TemplateBinding Padding}" Padding="{TemplateBinding Padding}"
Background="{TemplateBinding Background}" Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"> BorderThickness="{TemplateBinding BorderThickness}"
UseLayoutRounding="True">
<Grid HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"> <Grid HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ContentPresenter <ContentPresenter
Grid.Column="0"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
RecognizesAccessKey="True" RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /> SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
@@ -42,7 +47,7 @@
Margin="10,0,5,0" Margin="10,0,5,0"
HorizontalAlignment="Right" HorizontalAlignment="Right"
VerticalAlignment="Center" VerticalAlignment="Center"
Visibility="Hidden"> Visibility="Collapsed">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition /> <RowDefinition />
<RowDefinition /> <RowDefinition />
@@ -63,18 +68,52 @@
</Grid> </Grid>
</Grid> </Grid>
</Border> </Border>
<!-- 关键改动:用固定宽度的 Rectangle 画右侧竖线,永不消失 -->
<Rectangle
Width="1"
HorizontalAlignment="Right"
Fill="{TemplateBinding BorderBrush}"
SnapsToDevicePixels="False" />
<Thumb <Thumb
x:Name="PART_LeftHeaderGripper" x:Name="PART_LeftHeaderGripper"
Width="6"
HorizontalAlignment="Left" HorizontalAlignment="Left"
Background="Transparent"
Cursor="SizeWE" Cursor="SizeWE"
FocusVisualStyle="{x:Null}" FocusVisualStyle="{x:Null}">
Opacity="0" /> <Thumb.Style>
<Style TargetType="Thumb">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Thumb">
<Border Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Thumb.Style>
</Thumb>
<Thumb <Thumb
x:Name="PART_RightHeaderGripper" x:Name="PART_RightHeaderGripper"
Width="6"
HorizontalAlignment="Right" HorizontalAlignment="Right"
Background="Transparent"
Cursor="SizeWE" Cursor="SizeWE"
FocusVisualStyle="{x:Null}" FocusVisualStyle="{x:Null}">
Opacity="0" /> <Thumb.Style>
<Style TargetType="Thumb">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Thumb">
<Border Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Thumb.Style>
</Thumb>
</Grid> </Grid>
<ControlTemplate.Triggers> <ControlTemplate.Triggers>
<Trigger Property="SortDirection" Value="Ascending"> <Trigger Property="SortDirection" Value="Ascending">
@@ -88,7 +127,7 @@
<Setter TargetName="SortArrowDown" Property="Fill" Value="#61646D" /> <Setter TargetName="SortArrowDown" Property="Fill" Value="#61646D" />
</Trigger> </Trigger>
<Trigger Property="SortDirection" Value="{x:Null}"> <Trigger Property="SortDirection" Value="{x:Null}">
<Setter TargetName="SortArrowGrid" Property="Visibility" Value="Hidden" /> <Setter TargetName="SortArrowGrid" Property="Visibility" Value="Collapsed" />
</Trigger> </Trigger>
</ControlTemplate.Triggers> </ControlTemplate.Triggers>
</ControlTemplate> </ControlTemplate>
@@ -127,7 +166,6 @@
</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="White" />
</Trigger> </Trigger>
</ControlTemplate.Triggers> </ControlTemplate.Triggers>
@@ -137,9 +175,30 @@
</Style> </Style>
<Style x:Key="DefaultRowHeaderStyle" TargetType="{x:Type DataGridRowHeader}"> <Style x:Key="DefaultRowHeaderStyle" TargetType="{x:Type DataGridRowHeader}">
<Setter Property="BorderThickness" Value="0" /> <Setter Property="BorderBrush" Value="{Binding BorderBrush, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
<Setter Property="BorderThickness" Value="0,0,1,1" />
<Setter Property="FontSize" Value="{DynamicResource DefaultFontSize}" /> <Setter Property="FontSize" Value="{DynamicResource DefaultFontSize}" />
<Setter Property="FontFamily" Value="{DynamicResource FontFamily}" /> <Setter Property="FontFamily" Value="{DynamicResource FontFamily}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridRowHeader}">
<Border
Background="Transparent"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextElement.FontSize="10" />
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}}" Value="True">
<Setter Property="Foreground" Value="White" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style> </Style>
<Style x:Key="DefaultRowStyle" TargetType="{x:Type DataGridRow}"> <Style x:Key="DefaultRowStyle" TargetType="{x:Type DataGridRow}">
@@ -184,7 +243,8 @@
<Grid <Grid
x:Name="fousIcon" x:Name="fousIcon"
IsHitTestVisible="False" IsHitTestVisible="False"
Opacity="0"> Opacity="0"
Visibility="Collapsed">
<Path <Path
Width="10" Width="10"
Height="10" Height="10"
@@ -290,11 +350,12 @@
</Style> </Style>
<Style x:Key="DefaultDataGridStyle" TargetType="DataGrid"> <Style x:Key="DefaultDataGridStyle" TargetType="DataGrid">
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Background" Value="White" /> <Setter Property="Background" Value="White" />
<Setter Property="FocusVisualStyle" Value="{x:Null}" /> <Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="ColumnHeaderHeight" Value="36" /> <Setter Property="ColumnHeaderHeight" Value="36" />
<Setter Property="MinRowHeight" Value="40" /> <Setter Property="MinRowHeight" Value="40" />
<Setter Property="RowHeaderWidth" Value="0" />
<Setter Property="CanUserAddRows" Value="False" /> <Setter Property="CanUserAddRows" Value="False" />
<Setter Property="AutoGenerateColumns" Value="False" /> <Setter Property="AutoGenerateColumns" Value="False" />
<Setter Property="CanUserSortColumns" Value="True" /> <Setter Property="CanUserSortColumns" Value="True" />
@@ -325,7 +386,8 @@
Background="{TemplateBinding Background}" Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" BorderThickness="{TemplateBinding BorderThickness}"
SnapsToDevicePixels="True"> SnapsToDevicePixels="True"
UseLayoutRounding="True">
<ScrollViewer x:Name="DG_ScrollViewer" Focusable="false"> <ScrollViewer x:Name="DG_ScrollViewer" Focusable="false">
<ScrollViewer.Template> <ScrollViewer.Template>
<ControlTemplate TargetType="{x:Type ScrollViewer}"> <ControlTemplate TargetType="{x:Type ScrollViewer}">
@@ -340,13 +402,49 @@
<RowDefinition Height="*" /> <RowDefinition Height="*" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Border
Grid.Row="0"
Grid.Column="0"
Width="{Binding CellsPanelHorizontalOffset, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
Background="#eeeeee"
BorderBrush="{Binding BorderBrush, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
BorderThickness="1,0,1,1">
<CheckBox
Width="32"
HorizontalAlignment="Right"
VerticalAlignment="Center"
HorizontalContentAlignment="Center"
AutomationProperties.Name="全选行"
Command="{x:Static ext:StyledDataGrid.ToggleSelectAllCommand}"
CommandTarget="{Binding RelativeSource={RelativeSource AncestorType={x:Type ext:StyledDataGrid}}}"
IsChecked="{Binding AreAllRowsSelected, RelativeSource={RelativeSource AncestorType={x:Type ext:StyledDataGrid}}, Mode=OneWay}">
<CheckBox.Style>
<Style BasedOn="{StaticResource {x:Type CheckBox}}" TargetType="CheckBox">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ShowCheckBox, RelativeSource={RelativeSource AncestorType={x:Type ext:StyledDataGrid}}}" Value="True" />
<Condition Binding="{Binding ShowSelectAll, RelativeSource={RelativeSource AncestorType={x:Type ext:StyledDataGrid}}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter Property="Visibility" Value="Visible" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
</CheckBox.Style>
</CheckBox>
</Border>
<DataGridColumnHeadersPresenter <DataGridColumnHeadersPresenter
x:Name="PART_ColumnHeadersPresenter" x:Name="PART_ColumnHeadersPresenter"
Grid.Column="1" Grid.Column="1"
Grid.ColumnSpan="2" Grid.ColumnSpan="2"
Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Column}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" /> 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="1"> <Grid
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2">
<ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" /> <ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" />
<Grid <Grid
x:Name="NoDataTipsGrid" x:Name="NoDataTipsGrid"
@@ -433,4 +531,275 @@
</MultiTrigger> </MultiTrigger>
</Style.Triggers> </Style.Triggers>
</Style> </Style>
<FontFamily x:Key="FontFamily">fonts:GeistMono#Geist Mono, SF Mono, Menlo, Cascadia Mono, Consolas, DejaVu Sans Mono, Courier New, $Default</FontFamily>
<Style x:Key="StyledDefaultCellStyle" TargetType="DataGridCell">
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Padding" Value="8,0" />
<Setter Property="FontSize" Value="{DynamicResource DefaultFontSize}" />
<Setter Property="FontFamily" Value="{DynamicResource FontFamily}" />
<!--<Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGrid, Mode=FindAncestor}, Path=Foreground, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />-->
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid>
<Border
Padding="{TemplateBinding Padding}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ContentPresenter
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="{Binding SelectedRowForeground, RelativeSource={RelativeSource AncestorType={x:Type local:StyledDataGrid}}}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="StyledDefaultRowStyle" TargetType="{x:Type DataGridRow}">
<Setter Property="ContextMenu" Value="{Binding RowContextMenu, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" />
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" />
<Setter Property="BorderThickness" Value="0,0,1,0" />
<Setter Property="Background" Value="{x:Null}" />
<Setter Property="FontSize" Value="{DynamicResource DefaultFontSize}" />
<Setter Property="FontFamily" Value="{DynamicResource FontFamily}" />
<Setter Property="BorderBrush" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGrid, Mode=FindAncestor}, Path=BorderBrush}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridRow">
<Grid>
<Border
x:Name="border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" />
<SelectiveScrollingGrid>
<SelectiveScrollingGrid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</SelectiveScrollingGrid.ColumnDefinitions>
<SelectiveScrollingGrid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</SelectiveScrollingGrid.RowDefinitions>
<DataGridCellsPresenter
Grid.Column="1"
ItemsPanel="{TemplateBinding ItemsPanel}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
<DataGridDetailsPresenter
x:Name="DetailsPresenter"
Grid.Row="1"
Grid.Column="1"
SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical}, Converter={x:Static DataGrid.RowDetailsScrollingConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
Visibility="{TemplateBinding DetailsVisibility}" />
<DataGridRowHeader
Grid.RowSpan="2"
SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
</SelectiveScrollingGrid>
<Grid
x:Name="fousIcon"
IsHitTestVisible="False"
Opacity="0"
Visibility="Collapsed">
<Path
Width="10"
Height="10"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Data="M0,0 L0,0 50,0 50,10 10,10 10,50 0,50 0,52 z"
Fill="#4BB2FF"
RenderTransformOrigin="0.5,0.5"
Stretch="Fill">
<Path.RenderTransform>
<TransformGroup>
<ScaleTransform />
<SkewTransform />
<RotateTransform Angle="0" />
<TranslateTransform />
</TransformGroup>
</Path.RenderTransform>
</Path>
<Path
Width="10"
Height="10"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Data="M0,0 L0,0 50,0 50,10 10,10 10,50 0,50 0,52 z"
Fill="#4BB2FF"
RenderTransformOrigin="0.5,0.5"
Stretch="Fill">
<Path.RenderTransform>
<TransformGroup>
<ScaleTransform />
<SkewTransform />
<RotateTransform Angle="90" />
<TranslateTransform />
</TransformGroup>
</Path.RenderTransform>
</Path>
<Path
Width="10"
Height="10"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Data="M0,0 L0,0 50,0 50,10 10,10 10,50 0,50 0,52 z"
Fill="#4BB2FF"
RenderTransformOrigin="0.5,0.5"
Stretch="Fill">
<Path.RenderTransform>
<TransformGroup>
<ScaleTransform />
<SkewTransform />
<RotateTransform Angle="180" />
<TranslateTransform />
</TransformGroup>
</Path.RenderTransform>
</Path>
<Path
Width="10"
Height="10"
HorizontalAlignment="Left"
VerticalAlignment="Bottom"
Data="M0,0 L0,0 50,0 50,10 10,10 10,50 0,50 0,52 z"
Fill="#4BB2FF"
RenderTransformOrigin="0.5,0.5"
Stretch="Fill">
<Path.RenderTransform>
<TransformGroup>
<ScaleTransform />
<SkewTransform />
<RotateTransform Angle="-90" />
<TranslateTransform />
</TransformGroup>
</Path.RenderTransform>
</Path>
</Grid>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="fousIcon" Property="Opacity" Value="1" />
<Setter Property="Foreground" Value="{Binding SelectedRowForeground, RelativeSource={RelativeSource AncestorType={x:Type local:StyledDataGrid}}}" />
<Setter TargetName="border" Property="Background" Value="{Binding SelectedRowBackground, RelativeSource={RelativeSource AncestorType={x:Type local:StyledDataGrid}}}" />
</Trigger>
<Trigger Property="DetailsVisibility" Value="Visible">
<Setter TargetName="DetailsPresenter" Property="Margin" Value="0,0,1,0" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style
x:Key="StyledRowHeaderStyle"
BasedOn="{StaticResource DefaultRowHeaderStyle}"
TargetType="DataGridRowHeader">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridRowHeader">
<Border
Background="Transparent"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="0,0,1,1">
<Grid>
<ContentPresenter
x:Name="Number"
Margin="8,0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="{Binding Header, RelativeSource={RelativeSource AncestorType=DataGridRow}}"
Visibility="Collapsed" />
<CheckBox
x:Name="RowCheckBox"
HorizontalAlignment="Center"
VerticalAlignment="Center"
AutomationProperties.Name="选择行"
IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Visibility="Collapsed" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding ShowRowNumber, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" Value="True">
<Setter TargetName="Number" Property="Visibility" Value="Visible" />
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ShowCheckBox, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" Value="True" />
<Condition Binding="{Binding ShowRowNumber, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" Value="False" />
</MultiDataTrigger.Conditions>
<Setter TargetName="Number" Property="Visibility" Value="Collapsed" />
<Setter TargetName="RowCheckBox" Property="Visibility" Value="Visible" />
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ShowCheckBox, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" Value="True" />
<Condition Binding="{Binding IsSelectionModeActive, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter TargetName="Number" Property="Visibility" Value="Collapsed" />
<Setter TargetName="RowCheckBox" Property="Visibility" Value="Visible" />
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ShowCheckBox, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" Value="True" />
<Condition Binding="{Binding AreAllRowsSelected, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter TargetName="Number" Property="Visibility" Value="Collapsed" />
<Setter TargetName="RowCheckBox" Property="Visibility" Value="Visible" />
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ShowCheckBox, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" Value="True" />
<Condition Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter TargetName="Number" Property="Visibility" Value="Collapsed" />
<Setter TargetName="RowCheckBox" Property="Visibility" Value="Visible" />
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ShowCheckBox, RelativeSource={RelativeSource AncestorType=local:StyledDataGrid}}" Value="True" />
<Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=DataGridRow}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter TargetName="Number" Property="Visibility" Value="Collapsed" />
<Setter TargetName="RowCheckBox" Property="Visibility" Value="Visible" />
</MultiDataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style
x:Key="StyledNumberCellStyle"
BasedOn="{StaticResource StyledDefaultCellStyle}"
TargetType="DataGridCell">
<Setter Property="HorizontalContentAlignment" Value="Right" />
</Style>
<Style BasedOn="{StaticResource DefaultDataGridStyle}" TargetType="local:StyledDataGrid">
<Setter Property="EnableRowVirtualization" 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="SelectionUnit" Value="FullRow" />
<Setter Property="RowStyle" Value="{StaticResource StyledDefaultRowStyle}" />
<Setter Property="CellStyle" Value="{StaticResource StyledDefaultCellStyle}" />
<Setter Property="RowHeaderStyle" Value="{StaticResource StyledRowHeaderStyle}" />
</Style>
</ResourceDictionary> </ResourceDictionary>
+169
View File
@@ -0,0 +1,169 @@
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows;
namespace Main.Test;
/// <summary>配套图片列:自动使用所属 StyledDataGrid 的拖动暂停和图片缓存能力。</summary>
public class StyledDataGridImageColumn : DataGridBoundColumn
{
private static readonly Style DefaultImageStyle = CreateDefaultStyle();
/// <summary>可选的逐行占位图;未设置时显示空白。</summary>
public BindingBase? PlaceholderBinding { get; set; }
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
var image = new NetworkThumbnail { Style = ElementStyle ?? DefaultImageStyle };
if (Binding != null) BindingOperations.SetBinding(image, NetworkThumbnail.UrlProperty, Binding);
if (PlaceholderBinding != null)
BindingOperations.SetBinding(image, NetworkThumbnail.PlaceholderProperty, PlaceholderBinding);
return image;
}
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) => GenerateElement(cell, dataItem);
private static Style CreateDefaultStyle()
{
var style = new Style(typeof(NetworkThumbnail));
style.Setters.Add(new Setter(FrameworkElement.WidthProperty, 58d));
style.Setters.Add(new Setter(FrameworkElement.HeightProperty, 58d));
style.Setters.Add(new Setter(System.Windows.Controls.Image.StretchProperty, Stretch.Uniform));
style.Seal(); return style;
}
}
/// <summary>仅为已生成的可见单元格加载图片;回收时取消,避免旧图片覆盖新行。</summary>
public sealed class NetworkThumbnail : Image
{
public static readonly DependencyProperty CacheEnabledProperty = DependencyProperty.RegisterAttached("CacheEnabled", typeof(bool), typeof(NetworkThumbnail), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits, Changed));
public static bool GetCacheEnabled(DependencyObject target) => (bool)target.GetValue(CacheEnabledProperty);
public static void SetCacheEnabled(DependencyObject target, bool value) => target.SetValue(CacheEnabledProperty, value);
public static readonly DependencyProperty IsLoadingSuspendedProperty = DependencyProperty.RegisterAttached(
"IsLoadingSuspended", typeof(bool), typeof(NetworkThumbnail),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits, SuspensionChanged));
public static bool GetIsLoadingSuspended(DependencyObject target) => (bool)target.GetValue(IsLoadingSuspendedProperty);
public static void SetIsLoadingSuspended(DependencyObject target, bool value) => target.SetValue(IsLoadingSuspendedProperty, value);
private static void SuspensionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not NetworkThumbnail image) return;
image.CancelLoading();
image.Source = null;
if (!(bool)e.NewValue) image.QueueRefresh();
}
public static readonly DependencyProperty UrlProperty = DependencyProperty.Register(nameof(Url), typeof(string), typeof(NetworkThumbnail), new PropertyMetadata(null, Changed));
public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.Register(nameof(Placeholder), typeof(ImageSource), typeof(NetworkThumbnail), new PropertyMetadata(null, Changed));
public string? Url { get => (string?)GetValue(UrlProperty); set => SetValue(UrlProperty, value); }
public ImageSource? Placeholder { get => (ImageSource?)GetValue(PlaceholderProperty); set => SetValue(PlaceholderProperty, value); }
private CancellationTokenSource? loading;
private bool refreshPending;
public NetworkThumbnail()
{
Loaded += (_, _) => QueueRefresh();
Unloaded += (_, _) => CancelLoading();
}
private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not NetworkThumbnail image) return;
image.CancelLoading();
image.Source = GetIsLoadingSuspended(image) ? null : image.Placeholder;
// 回收行时多个绑定会依次变更,等本轮绑定完成后只加载一次新 URL。
image.QueueRefresh();
}
private void QueueRefresh()
{
if (!IsLoaded || refreshPending) return;
refreshPending = true;
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Loaded, new Action(() =>
{
refreshPending = false;
if (IsLoaded) StartLoading();
}));
}
private void CancelLoading()
{
loading?.Cancel(); loading?.Dispose(); loading = null;
}
private async void StartLoading()
{
CancelLoading(); ToolTip = null;
if (GetIsLoadingSuspended(this)) { Source = null; return; }
Source = Placeholder;
if (string.IsNullOrWhiteSpace(Url)) return;
var request = new CancellationTokenSource(); loading = request;
var token = request.Token;
try
{
var bitmap = await ThumbnailLoader.LoadAsync(Url, GetCacheEnabled(this), token);
if (!token.IsCancellationRequested && ReferenceEquals(loading, request)) Source = bitmap;
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
catch (Exception ex)
{
if (!token.IsCancellationRequested && ReferenceEquals(loading, request)) ToolTip = $"图片加载失败:{ex.Message}";
}
}
}
internal static class ThumbnailLoader
{
private static readonly HttpClient Client = new() { Timeout = TimeSpan.FromSeconds(12) };
private static readonly SemaphoreSlim Slots = new(4);
private static readonly object CacheLock = new();
private static readonly Dictionary<string, BitmapSource> Cache = new();
private static readonly Queue<string> CacheOrder = new();
private static long started, succeeded, failed, canceled, cacheHits, bytes, totalTicks;
private static int active, pending;
public static int Pending => Volatile.Read(ref pending);
public static string Statistics => $"网络图片:请求 {Interlocked.Read(ref started)} / 成功 {Interlocked.Read(ref succeeded)} / 失败 {Interlocked.Read(ref failed)} / 取消 {Interlocked.Read(ref canceled)} / 缓存命中 {Interlocked.Read(ref cacheHits)} | 活跃 {Volatile.Read(ref active)},待完成 {Pending} | 下载 {Interlocked.Read(ref bytes) / 1024d:N0} KB | 成功平均 {AverageMilliseconds:N0} ms";
private static double AverageMilliseconds => Interlocked.Read(ref succeeded) == 0 ? 0 : Interlocked.Read(ref totalTicks) * 1000d / Stopwatch.Frequency / Interlocked.Read(ref succeeded);
public static async Task<BitmapSource> LoadAsync(string url, bool cacheEnabled, CancellationToken token)
{
var cacheKey = url;
lock (CacheLock)
if (cacheEnabled && Cache.TryGetValue(cacheKey, out var cached)) { Interlocked.Increment(ref cacheHits); return cached; }
Interlocked.Increment(ref pending);
var acquired = false;
try
{
await Slots.WaitAsync(token).ConfigureAwait(false); acquired = true;
Interlocked.Increment(ref active); Interlocked.Increment(ref started);
var watch = Stopwatch.StartNew();
var data = await Client.GetByteArrayAsync(url, token).ConfigureAwait(false);
Interlocked.Add(ref bytes, data.Length);
var bitmap = await Task.Run(() =>
{
token.ThrowIfCancellationRequested();
using var stream = new MemoryStream(data);
var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad;
image.DecodePixelWidth = 72; image.StreamSource = stream; image.EndInit(); image.Freeze();
return image;
}, token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
lock (CacheLock)
{
if (cacheEnabled && !Cache.ContainsKey(cacheKey))
{
if (Cache.Count >= 128) Cache.Remove(CacheOrder.Dequeue());
Cache.Add(cacheKey, bitmap); CacheOrder.Enqueue(cacheKey);
}
}
Interlocked.Increment(ref succeeded); Interlocked.Add(ref totalTicks, watch.ElapsedTicks);
return bitmap;
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { Interlocked.Increment(ref canceled); throw; }
catch { Interlocked.Increment(ref failed); throw; }
finally
{
if (acquired) { Interlocked.Decrement(ref active); Slots.Release(); }
Interlocked.Decrement(ref pending);
}
}
}
+52 -26
View File
@@ -1,38 +1,64 @@
using Bogus; using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows;
using MAX.Core.Logger; using MAX.Core.Logger;
using System; using Prism.Commands;
using System.Collections.Generic; using Prism.Mvvm;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trade.Framework.Services; using Trade.Framework.Services;
namespace Main.Test.ViewModels; namespace Main.Test.ViewModels;
internal class MainViewModel internal class MainViewModel : BindableBase
{ {
private readonly ILoggerFacade _logger; private List<ItemInfo> data = DemoData.Create(10000);
public List<ItemInfo> Data { get; set; } public List<ItemInfo> Data { get => data; private set => SetProperty(ref data, value); }
private string actionMessage = "可右键查看详情、复制编码或切换状态;默认加载 10,000 行。";
public string ActionMessage { get => actionMessage; private set => SetProperty(ref actionMessage, value); }
private ObservableCollection<ItemInfo> selectedItems = new();
public ObservableCollection<ItemInfo> SelectedItems
{
get => selectedItems;
set
{
ArgumentNullException.ThrowIfNull(value);
if (ReferenceEquals(selectedItems, value)) return;
selectedItems.CollectionChanged -= SelectionChanged;
SetProperty(ref selectedItems, value);
selectedItems.CollectionChanged += SelectionChanged;
RaisePropertyChanged(nameof(SelectedCount));
}
}
public int SelectedCount => SelectedItems.Count;
public int NetworkImageSize { get; set; }
public DelegateCommand<ItemInfo> DetailCommand { get; }
public DelegateCommand<ItemInfo> ConfirmCommand { get; }
public DelegateCommand<ItemInfo> CopyCodeCommand { get; }
public MainViewModel(ILoggerFacade logger, UserManager userManager) public MainViewModel(ILoggerFacade logger, UserManager userManager)
{ {
_logger = logger; selectedItems.CollectionChanged += SelectionChanged;
_logger.Info("123123"); DetailCommand = new(item => { if (item != null) ActionMessage = $"详情:{item.Code} · {item.Name} · ¥{item.Value} · {item.Buyer} · {item.Status}"; });
ConfirmCommand = new(item =>
{
if (item == null) return;
item.Status = item.Status == "已确认" ? "待处理" : "已确认";
ActionMessage = $"已更新 {item.Code}:{item.Status}";
});
CopyCodeCommand = new(item =>
{
if (item == null) return;
try { Clipboard.SetText(item.Code.ToString()); ActionMessage = $"已复制编码 {item.Code}"; }
catch (System.Runtime.InteropServices.ExternalException) { ActionMessage = "剪贴板正忙,请重试。"; }
});
}
private void SelectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => RaisePropertyChanged(nameof(SelectedCount));
public async Task LoadAsync(int count)
{
// 创建 Faker 并配置规则 if (count is < 1 or > 50000) throw new ArgumentOutOfRangeException(nameof(count));
var itemFaker = new Faker<ItemInfo>() var imageSize = NetworkImageSize;
.RuleFor(x => x.Code, f => f.Random.Int(1000, 9999)) // 4位随机编码 var rows = await Task.Run(() => DemoData.Create(count, imageSize));
.RuleFor(x => x.Name, f => f.Commerce.ProductName()) // 商品名称 SelectedItems.Clear(); Data = rows;
.RuleFor(x => x.Value, f => f.Commerce.Price().ToString()) // 商品价格 ActionMessage = $"已加载 {count:N0} 行;" + (imageSize == 0 ? "本地缩略图。" : $"Picsum {imageSize}×{imageSize} 网络随机图,可见时加载。每次重新加载使用新种子。冷 / 热测试以当前页面已加载状态为准。");
.RuleFor(x => x.Qty, f => f.Random.Int(1, 100)); // 1-100的随机数量
// 生成单个对象
var singleItem = itemFaker.Generate();
// 生成100个对象
Data = itemFaker.Generate(100);
//Data.Clear();
} }
} }
@@ -8,7 +8,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" /> <PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="HandyControl" Version="3.6.0.9" /> <PackageReference Include="HandyControl" Version="3.6.2" />
</ItemGroup> </ItemGroup>
+4 -4
View File
@@ -186,8 +186,8 @@ namespace TemuKJD.ToolForms
this.pictureBox1.Image = ImageBuild.LoadBitmapLoadBitmipImageFromUrl(orderItem.thumb_img); this.pictureBox1.Image = ImageBuild.LoadBitmapLoadBitmipImageFromUrl(orderItem.thumb_img);
this.txtShopSkuId.Text = orderItem.sku_id; this.txtShopSkuId.Text = orderItem.sku_id;
this.txtShopGoodsId.Text = orderItem.product_id; this.txtShopGoodsId.Text = orderItem.product_id;
this.txtUpSpuCode.Text = orderItem.out_product_id.IsNullOrEmpty() ? orderItem.product_id : orderItem.out_product_id; this.txtSpuCode.Text = orderItem.out_product_id.IsNullOrEmpty() ? orderItem.product_id : orderItem.out_product_id;
this.txtUpSkuCode.Text = orderItem.out_sku_id.IsNullOrEmpty() ? orderItem.sku_attr_str : orderItem.out_sku_id; this.txtSkuCode.Text = orderItem.out_sku_id.IsNullOrEmpty() ? orderItem.sku_attr_str : orderItem.out_sku_id;
this.txtShopGoodsName.Text = orderItem.title; this.txtShopGoodsName.Text = orderItem.title;
this.txtShopSpecName.Text = orderItem.sku_attr_str; this.txtShopSpecName.Text = orderItem.sku_attr_str;
this.txtShopOrderItemCnt.Text = orderItem.sku_cnt.ParseToString(); this.txtShopOrderItemCnt.Text = orderItem.sku_cnt.ParseToString();
@@ -944,8 +944,8 @@ namespace TemuKJD.ToolForms
} }
string url; string url;
string upSpuCode = txtUpSpuCode.Text.Trim(); string upSpuCode = txtSpuCode.Text.Trim();
string upSkuCode = txtUpSkuCode.Text.Trim(); string upSkuCode = txtSkuCode.Text.Trim();
// 保存sku及商品关联信息 // 保存sku及商品关联信息
var data = UserLogin.GetSignaturex() var data = UserLogin.GetSignaturex()
+ "&spu_code=" + GetHtml.UrlEncodeUtf8(upSpuCode) + "&spu_code=" + GetHtml.UrlEncodeUtf8(upSpuCode)
+17 -17
View File
@@ -57,9 +57,9 @@
this.txtShopSpecName = new System.Windows.Forms.TextBox(); this.txtShopSpecName = new System.Windows.Forms.TextBox();
this.label14 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label();
this.txtUpSpuCode = new System.Windows.Forms.TextBox(); this.txtSpuCode = new System.Windows.Forms.TextBox();
this.label12 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label();
this.txtUpSkuCode = new System.Windows.Forms.TextBox(); this.txtSkuCode = new System.Windows.Forms.TextBox();
this.label11 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label();
this.txtShopSkuId = new System.Windows.Forms.TextBox(); this.txtShopSkuId = new System.Windows.Forms.TextBox();
this.label10 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label();
@@ -470,11 +470,11 @@
// //
// txtUpSpuCode // txtUpSpuCode
// //
this.txtUpSpuCode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtSpuCode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtUpSpuCode.Location = new System.Drawing.Point(85, 228); this.txtSpuCode.Location = new System.Drawing.Point(85, 228);
this.txtUpSpuCode.Name = "txtUpSpuCode"; this.txtSpuCode.Name = "txtUpSpuCode";
this.txtUpSpuCode.Size = new System.Drawing.Size(152, 23); this.txtSpuCode.Size = new System.Drawing.Size(152, 23);
this.txtUpSpuCode.TabIndex = 814; this.txtSpuCode.TabIndex = 814;
// //
// label12 // label12
// //
@@ -487,13 +487,13 @@
// //
// txtUpSkuCode // txtUpSkuCode
// //
this.txtUpSkuCode.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) this.txtSkuCode.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right))); | System.Windows.Forms.AnchorStyles.Right)));
this.txtUpSkuCode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtSkuCode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtUpSkuCode.Location = new System.Drawing.Point(321, 228); this.txtSkuCode.Location = new System.Drawing.Point(321, 228);
this.txtUpSkuCode.Name = "txtUpSkuCode"; this.txtSkuCode.Name = "txtUpSkuCode";
this.txtUpSkuCode.Size = new System.Drawing.Size(152, 23); this.txtSkuCode.Size = new System.Drawing.Size(152, 23);
this.txtUpSkuCode.TabIndex = 812; this.txtSkuCode.TabIndex = 812;
// //
// label11 // label11
// //
@@ -779,8 +779,8 @@
this.panel1.Controls.Add(this.label10); this.panel1.Controls.Add(this.label10);
this.panel1.Controls.Add(this.txtShopSkuId); this.panel1.Controls.Add(this.txtShopSkuId);
this.panel1.Controls.Add(this.label11); this.panel1.Controls.Add(this.label11);
this.panel1.Controls.Add(this.txtUpSpuCode); this.panel1.Controls.Add(this.txtSpuCode);
this.panel1.Controls.Add(this.txtUpSkuCode); this.panel1.Controls.Add(this.txtSkuCode);
this.panel1.Controls.Add(this.label12); this.panel1.Controls.Add(this.label12);
this.panel1.Controls.Add(this.pnlMap); this.panel1.Controls.Add(this.pnlMap);
this.panel1.Location = new System.Drawing.Point(867, 3); this.panel1.Location = new System.Drawing.Point(867, 3);
@@ -1201,9 +1201,9 @@
private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox txtShopGoodsName; private System.Windows.Forms.TextBox txtShopGoodsName;
private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox txtUpSpuCode; private System.Windows.Forms.TextBox txtSpuCode;
private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label12;
private System.Windows.Forms.TextBox txtUpSkuCode; private System.Windows.Forms.TextBox txtSkuCode;
private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label13;
private System.Windows.Forms.TextBox txtShopSpecName; private System.Windows.Forms.TextBox txtShopSpecName;
@@ -477,8 +477,11 @@ namespace Work._29Tools.Forms.UserForms
"充值", "充值",
"管理员充值", "管理员充值",
"支付宝充值", "支付宝充值",
"礼物单支出/礼物单退费",
"拍单扣除/作废返还", "拍单扣除/作废返还",
"超重扣费"}); "超重扣费支出",
"退货包裹扣费支出",
"云仓退货扣费支出"});
this.cmbType.Location = new System.Drawing.Point(42, 33); this.cmbType.Location = new System.Drawing.Point(42, 33);
this.cmbType.Name = "cmbType"; this.cmbType.Name = "cmbType";
this.cmbType.Size = new System.Drawing.Size(121, 25); this.cmbType.Size = new System.Drawing.Size(121, 25);
@@ -152,14 +152,20 @@ namespace Work._29Tools.Forms.UserForms
data3 += "&create_time_end=" + dtpTimeEnd.Value.ToString("yyyy-MM-dd HH:mm:ss"); data3 += "&create_time_end=" + dtpTimeEnd.Value.ToString("yyyy-MM-dd HH:mm:ss");
if (cmbType.Text == "充值") if (cmbType.Text == "充值")
data3 += "&type_in=1,30"; data3 += "&type_in=1,30";
if (cmbType.Text == "管理员充值") else if (cmbType.Text == "管理员充值")
data3 += "&type_in=1"; data3 += "&type_in=1";
if (cmbType.Text == "支付宝充值") else if (cmbType.Text == "支付宝充值")
data3 += "&type_in=30"; data3 += "&type_in=30";
if (cmbType.Text == "拍单扣除/作废返还") else if (cmbType.Text == "礼物单支出/礼物单退费")
data3 += "&type_in=16,34";
else if (cmbType.Text == "拍单扣除/作废返还")
data3 += "&type_in=20,23"; data3 += "&type_in=20,23";
if (cmbType.Text == "超重扣费") else if (cmbType.Text == "超重扣费支出")
data3 += "&type_in=24"; data3 += "&type_in=24";
else if (cmbType.Text == "退货包裹扣费支出")
data3 += "&type_in=26";
else if (cmbType.Text == "云仓退货扣费支出")
data3 += "&type_in=31";
if (!string.IsNullOrEmpty(txtOutOrderId.Text.Trim())) if (!string.IsNullOrEmpty(txtOutOrderId.Text.Trim()))
data3 += "&order_id_in=" + txtOutOrderId.Text.Trim(); data3 += "&order_id_in=" + txtOutOrderId.Text.Trim();
if (!string.IsNullOrEmpty(txtShopOrderNo.Text.Trim())) if (!string.IsNullOrEmpty(txtShopOrderNo.Text.Trim()))