统计页面 修改店铺选择,增加店铺搜索Combobox

This commit is contained in:
chfei committed 2026-08-07 11:25:19 +08:00
1 parent b6b72e6bc3
commit f12a7f14ea
16 files changed
+1801 -41

No files matched your search

@@ -0,0 +1,315 @@
<UserControl x:Class="_29WxOrderWpf.Ctrls.Commons.ShopFilterComboBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
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"
mc:Ignorable="d"
x:Name="Root"
MinHeight="30"
KeyDown="Root_KeyDown"
d:DesignWidth="220"
d:DesignHeight="32">
<UserControl.Resources>
<!-- 下拉按钮外观:与 BaseComboBox 类似的白底圆角 + 右侧箭头 -->
<ControlTemplate x:Key="DropDownToggleTemplate" TargetType="ToggleButton">
<Border x:Name="bd"
Background="White"
BorderBrush="#FFACACAC"
BorderThickness="1"
CornerRadius="4"
SnapsToDevicePixels="True">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding HeaderText}"
Margin="10,0,6,0"
VerticalAlignment="Center"
FontSize="14"
Foreground="#FF333333"
TextTrimming="CharacterEllipsis"
ToolTip="{Binding HeaderText}" />
<Path x:Name="ArrowPath"
Grid.Column="1"
Margin="0,0,10,0"
VerticalAlignment="Center"
Data="M 0 0 L 4 4 L 8 0"
Stroke="#FF606060"
StrokeThickness="1.5"
Fill="White">
<Path.RenderTransform>
<RotateTransform Angle="0" CenterX="4" CenterY="2" />
</Path.RenderTransform>
</Path>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bd" Property="BorderBrush" Value="#FF7EB4EA" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="bd" Property="BorderBrush" Value="#FF569DE5" />
<Setter TargetName="bd" Property="Background" Value="#FFF5F9FF" />
<Setter TargetName="ArrowPath" Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="180" CenterX="4" CenterY="2" />
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="bd" Property="Background" Value="#FFF0F0F0" />
<Setter TargetName="bd" Property="BorderBrush" Value="#FFD9D9D9" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</UserControl.Resources>
<Grid x:Name="RootGrid">
<ToggleButton x:Name="DropDownToggle"
Focusable="True"
Template="{StaticResource DropDownToggleTemplate}" />
<Popup x:Name="DropDownPopup"
IsOpen="{Binding IsChecked, ElementName=DropDownToggle, Mode=TwoWay}"
StaysOpen="False"
AllowsTransparency="True"
Placement="Bottom"
PlacementTarget="{Binding ElementName=RootGrid}"
VerticalOffset="4"
PopupAnimation="Fade"
Opened="DropDownPopup_Opened">
<Border x:Name="DropDownRoot"
Background="White"
BorderBrush="#FFBFBFBF"
BorderThickness="1"
CornerRadius="6"
MaxWidth="420"
Focusable="True"
PreviewKeyDown="DropDownRoot_PreviewKeyDown">
<Border.Effect>
<DropShadowEffect BlurRadius="12" ShadowDepth="3" Opacity="0.18" Color="#000000" />
</Border.Effect>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- 搜索框 -->
<Border Grid.Row="0" Padding="10,10,10,6">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsSearchable}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<Grid>
<TextBox x:Name="SearchTextBox"
Padding="8,6"
FontSize="13"
VerticalContentAlignment="Center"
BorderBrush="#FFD0D0D0"
BorderThickness="1"
TextChanged="SearchTextBox_TextChanged" />
<TextBlock x:Name="SearchWaterMark"
Text="{Binding SearchPlaceholder}"
Margin="10,0"
VerticalAlignment="Center"
FontSize="13"
Foreground="#FF999999"
IsHitTestVisible="False">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=SearchTextBox}" Value="">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
</Border>
<!-- 全部商铺 -->
<Border Grid.Row="1" Padding="10,4" Background="#FFFAFAFA" BorderBrush="#FFEEEEEE" BorderThickness="0,1,0,1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<CheckBox x:Name="SelectAllCheckBox"
Content="{Binding SelectAllText}"
FontSize="13"
FontWeight="Bold"
VerticalAlignment="Center"
IsThreeState="True"
Click="SelectAllCheckBox_Click" />
<TextBlock Grid.Column="1"
Text="{Binding TotalCountText}"
Margin="8,0,0,0"
VerticalAlignment="Center"
FontSize="12"
Foreground="#FF888888" />
</Grid>
</Border>
<!-- 分组列表 -->
<ScrollViewer Grid.Row="2"
MaxHeight="{Binding MaxDropDownHeight}"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
<ItemsControl ItemsSource="{Binding DropDownGroups}" Margin="0,2,0,2">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<!-- 分组头 -->
<Border x:Name="GroupHeaderBorder"
Padding="10,5"
Background="#FFF7F7F7"
Cursor="Hand"
MouseLeftButtonDown="GroupHeader_MouseLeftButtonDown">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsHeaderVisible}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center"
Margin="0,0,6,0"
FontSize="10"
Foreground="#FF666666">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Text" Value="&#9654;" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsExpanded}" Value="True">
<Setter Property="Text" Value="&#9660;" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<CheckBox Grid.Column="1"
VerticalAlignment="Center"
Margin="0,0,8,0"
IsThreeState="True"
IsChecked="{Binding IsChecked}" />
<TextBlock Grid.Column="2"
Text="{Binding Name}"
VerticalAlignment="Center"
FontSize="13"
FontWeight="Bold"
Foreground="#FF333333" />
<TextBlock Grid.Column="3"
Text="{Binding CountText}"
VerticalAlignment="Center"
FontSize="12"
Foreground="#FF888888" />
</Grid>
</Border>
<!-- 分组项 -->
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.Style>
<Style TargetType="ItemsControl">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsExpanded}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</ItemsControl.Style>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="30,1,10,1">
<Grid.Style>
<Style TargetType="Grid">
<Setter Property="Background" Value="Transparent" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsHighlighted}" Value="True">
<Setter Property="Background" Value="#FFE3F0FF" />
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<CheckBox Content="{Binding DisplayName}"
IsChecked="{Binding IsSelected}"
Padding="4,3"
FontSize="13"
VerticalContentAlignment="Center"
Foreground="#FF333333"
Click="ItemCheckBox_Click" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<!-- 底部:已选择 + 清空/全选/确定 -->
<Border Grid.Row="3" Padding="10,8" Background="#FFFAFAFA" BorderBrush="#FFEEEEEE" BorderThickness="0,1,0,0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding SelectedCountText}"
VerticalAlignment="Center"
FontSize="13"
Foreground="#FF555555" />
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button Content="清空"
Padding="12,4"
Margin="4,0,0,0"
FontSize="13"
Style="{StaticResource BasePageButtonLightStyle}"
Click="ClearButton_Click" />
<Button Content="全选"
Padding="12,4"
Margin="8,0,0,0"
FontSize="13"
Style="{StaticResource BasePageButtonLightStyle}"
Click="SelectAllButton_Click" />
<Button Content="确定"
Padding="14,4"
Margin="8,0,0,0"
FontSize="13"
Style="{StaticResource BasePageButtonStyle}"
Click="ConfirmButton_Click" />
</StackPanel>
</Grid>
</Border>
</Grid>
</Border>
</Popup>
</Grid>
</UserControl>
@@ -0,0 +1,869 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using TinyPinyin;
namespace _29WxOrderWpf.Ctrls.Commons
{
/// <summary>
/// 商铺筛选 ComboBox 控件。
/// 只需绑定:
/// ItemsSource 数据源(如 ObservableCollection&lt;ShopOption&gt;)
/// SelectedItems 选中的项集合(TwoWay,如 ObservableCollection&lt;ShopOption&gt;)
/// DisplayMemberPath 显示名称的属性路径(如 ShopName)
/// IsSearchable 是否显示搜索框(默认 true)
/// IsGrouped 是否按分组显示(默认 false)
/// GroupByPath 分组名称的属性路径(IsGrouped=true 时生效,如 Region)
/// 搜索支持中文、全拼、拼音首字母;键盘:
/// ↑/↓ 选择(移动高亮),空格 选中/取消,Enter 确定,Esc 取消(还原打开前的选择)。
/// </summary>
public partial class ShopFilterComboBox : UserControl, INotifyPropertyChanged
{
private readonly ObservableCollection<ShopFilterGroup> _groups = new ObservableCollection<ShopFilterGroup>();
private readonly List<ShopFilterGroup> _allGroups = new List<ShopFilterGroup>();
private readonly List<ShopFilterItem> _allItems = new List<ShopFilterItem>();
private readonly List<ShopFilterItem> _visibleItems = new List<ShopFilterItem>();
private ShopFilterItem _highlightedItem;
private List<object> _openedSnapshot;
private bool _syncing;
private INotifyCollectionChanged _itemsNotifier;
private INotifyCollectionChanged _selectedNotifier;
public ShopFilterComboBox()
{
InitializeComponent();
// 内部 UI 统一绑定到控件自身(外部 ItemsSource/SelectedItems 等仍绑定在控件上,不受影响)
RootGrid.DataContext = this;
DropDownRoot.DataContext = this;
SelectedItems = new ObservableCollection<object>();
}
#region 依赖属性
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register(nameof(ItemsSource), typeof(IEnumerable), typeof(ShopFilterComboBox),
new PropertyMetadata(null, OnItemsSourceChanged));
/// <summary>数据源</summary>
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register(nameof(SelectedItems), typeof(IList), typeof(ShopFilterComboBox),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemsChanged));
/// <summary>选中的项集合(双向绑定,元素为 ItemsSource 中的原始对象)</summary>
public IList SelectedItems
{
get { return (IList)GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
public static readonly DependencyProperty DisplayMemberPathProperty =
DependencyProperty.Register(nameof(DisplayMemberPath), typeof(string), typeof(ShopFilterComboBox),
new PropertyMetadata(null, OnViewPropertyChanged));
/// <summary>显示名称的属性路径(如 ShopName)</summary>
public string DisplayMemberPath
{
get { return (string)GetValue(DisplayMemberPathProperty); }
set { SetValue(DisplayMemberPathProperty, value); }
}
public static readonly DependencyProperty IsSearchableProperty =
DependencyProperty.Register(nameof(IsSearchable), typeof(bool), typeof(ShopFilterComboBox),
new PropertyMetadata(true));
/// <summary>是否显示搜索框</summary>
public bool IsSearchable
{
get { return (bool)GetValue(IsSearchableProperty); }
set { SetValue(IsSearchableProperty, value); }
}
public static readonly DependencyProperty IsGroupedProperty =
DependencyProperty.Register(nameof(IsGrouped), typeof(bool), typeof(ShopFilterComboBox),
new PropertyMetadata(false, OnViewPropertyChanged));
/// <summary>是否按分组显示</summary>
public bool IsGrouped
{
get { return (bool)GetValue(IsGroupedProperty); }
set { SetValue(IsGroupedProperty, value); }
}
public static readonly DependencyProperty GroupByPathProperty =
DependencyProperty.Register(nameof(GroupByPath), typeof(string), typeof(ShopFilterComboBox),
new PropertyMetadata(null, OnViewPropertyChanged));
/// <summary>分组名称的属性路径(IsGrouped=true 时生效,如 Region)</summary>
public string GroupByPath
{
get { return (string)GetValue(GroupByPathProperty); }
set { SetValue(GroupByPathProperty, value); }
}
public static readonly DependencyProperty AllTextProperty =
DependencyProperty.Register(nameof(AllText), typeof(string), typeof(ShopFilterComboBox),
new PropertyMetadata("全部商铺"));
/// <summary>未选择或全部选择时头部显示的文本(默认“全部商铺”)</summary>
public string AllText
{
get { return (string)GetValue(AllTextProperty); }
set { SetValue(AllTextProperty, value); }
}
public static readonly DependencyProperty UnitTextProperty =
DependencyProperty.Register(nameof(UnitText), typeof(string), typeof(ShopFilterComboBox),
new PropertyMetadata("个商铺"));
/// <summary>头部数量单位(默认“个商铺”,显示如“8 个商铺”)</summary>
public string UnitText
{
get { return (string)GetValue(UnitTextProperty); }
set { SetValue(UnitTextProperty, value); }
}
public static readonly DependencyProperty CountSuffixProperty =
DependencyProperty.Register(nameof(CountSuffix), typeof(string), typeof(ShopFilterComboBox),
new PropertyMetadata("家", OnViewPropertyChanged));
/// <summary>数量单位后缀(默认“家”,显示如“共28家”“12家”“已选择:8 家”)</summary>
public string CountSuffix
{
get { return (string)GetValue(CountSuffixProperty); }
set { SetValue(CountSuffixProperty, value); }
}
public static readonly DependencyProperty SelectAllTextProperty =
DependencyProperty.Register(nameof(SelectAllText), typeof(string), typeof(ShopFilterComboBox),
new PropertyMetadata("全部商铺"));
/// <summary>“全部”复选框文案(默认“全部商铺”)</summary>
public string SelectAllText
{
get { return (string)GetValue(SelectAllTextProperty); }
set { SetValue(SelectAllTextProperty, value); }
}
public static readonly DependencyProperty SearchPlaceholderProperty =
DependencyProperty.Register(nameof(SearchPlaceholder), typeof(string), typeof(ShopFilterComboBox),
new PropertyMetadata("搜索商铺..."));
/// <summary>搜索框占位文案</summary>
public string SearchPlaceholder
{
get { return (string)GetValue(SearchPlaceholderProperty); }
set { SetValue(SearchPlaceholderProperty, value); }
}
public static readonly DependencyProperty MaxDropDownHeightProperty =
DependencyProperty.Register(nameof(MaxDropDownHeight), typeof(double), typeof(ShopFilterComboBox),
new PropertyMetadata(300.0));
/// <summary>下拉列表最大高度</summary>
public double MaxDropDownHeight
{
get { return (double)GetValue(MaxDropDownHeightProperty); }
set { SetValue(MaxDropDownHeightProperty, value); }
}
public static readonly DependencyProperty ExpandGroupsByDefaultProperty =
DependencyProperty.Register(nameof(ExpandGroupsByDefault), typeof(bool), typeof(ShopFilterComboBox),
new PropertyMetadata(true));
/// <summary>分组默认是否展开</summary>
public bool ExpandGroupsByDefault
{
get { return (bool)GetValue(ExpandGroupsByDefaultProperty); }
set { SetValue(ExpandGroupsByDefaultProperty, value); }
}
#endregion
#region 路由事件
public static readonly RoutedEvent SelectionChangedEvent =
EventManager.RegisterRoutedEvent("SelectionChanged", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(ShopFilterComboBox));
/// <summary>选中集合内容变化时触发</summary>
public event RoutedEventHandler SelectionChanged
{
add { AddHandler(SelectionChangedEvent, value); }
remove { RemoveHandler(SelectionChangedEvent, value); }
}
public static readonly RoutedEvent ConfirmedEvent =
EventManager.RegisterRoutedEvent("Confirmed", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(ShopFilterComboBox));
/// <summary>点击“确定”或按 Enter 时触发(可在此执行查询)</summary>
public event RoutedEventHandler Confirmed
{
add { AddHandler(ConfirmedEvent, value); }
remove { RemoveHandler(ConfirmedEvent, value); }
}
public static readonly RoutedEvent CancelledEvent =
EventManager.RegisterRoutedEvent("Cancelled", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(ShopFilterComboBox));
/// <summary>按 Esc 取消时触发(已还原打开前的选择)</summary>
public event RoutedEventHandler Cancelled
{
add { AddHandler(CancelledEvent, value); }
remove { RemoveHandler(CancelledEvent, value); }
}
#endregion
#region 内部绑定属性
/// <summary>当前显示的分组集合</summary>
public ObservableCollection<ShopFilterGroup> DropDownGroups
{
get { return _groups; }
}
/// <summary>头部文本(全部商铺 / N 个商铺)</summary>
public string HeaderText
{
get
{
var sel = SelectedItems;
int total = _allItems.Count;
int count = sel == null ? 0 : sel.Count;
if (count == 0 || (total > 0 && count >= total)) return AllText;
return count + " " + UnitText;
}
}
/// <summary>总数文本(如“共28家”)</summary>
public string TotalCountText
{
get { return "共" + _allItems.Count + CountSuffix; }
}
/// <summary>已选择文本(如“已选择:8 家”)</summary>
public string SelectedCountText
{
get { return "已选择:" + (SelectedItems == null ? 0 : SelectedItems.Count) + " " + CountSuffix; }
}
#endregion
#region 依赖属性回调
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var c = (ShopFilterComboBox)d;
c.UnsubscribeItems();
c.SubscribeItems();
c.Rebuild();
}
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var c = (ShopFilterComboBox)d;
c.UnsubscribeSelected();
c.SubscribeSelected();
c.OnSelectionContentChanged();
}
private static void OnViewPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((ShopFilterComboBox)d).Rebuild();
}
private void SubscribeItems()
{
_itemsNotifier = ItemsSource as INotifyCollectionChanged;
if (_itemsNotifier != null) _itemsNotifier.CollectionChanged += OnItemsSourceCollectionChanged;
}
private void UnsubscribeItems()
{
if (_itemsNotifier != null) _itemsNotifier.CollectionChanged -= OnItemsSourceCollectionChanged;
_itemsNotifier = null;
}
private void SubscribeSelected()
{
_selectedNotifier = SelectedItems as INotifyCollectionChanged;
if (_selectedNotifier != null) _selectedNotifier.CollectionChanged += OnSelectedItemsCollectionChanged;
}
private void UnsubscribeSelected()
{
if (_selectedNotifier != null) _selectedNotifier.CollectionChanged -= OnSelectedItemsCollectionChanged;
_selectedNotifier = null;
}
private void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Rebuild();
}
private void OnSelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (_syncing) return;
_syncing = true;
try { SyncItemStatesFromSelection(); }
finally { _syncing = false; }
RefreshSelectionState();
RaiseSelectionChanged();
}
#endregion
#region 构建与过滤
private void Rebuild()
{
_allItems.Clear();
_allGroups.Clear();
bool grouped = IsGrouped && !string.IsNullOrEmpty(GroupByPath);
Dictionary<string, ShopFilterGroup> groupMap = null;
ShopFilterGroup flatGroup = null;
if (grouped)
{
groupMap = new Dictionary<string, ShopFilterGroup>(StringComparer.Ordinal);
}
else
{
flatGroup = new ShopFilterGroup { Name = string.Empty, CountSuffix = CountSuffix, IsExpanded = true };
_allGroups.Add(flatGroup);
}
var source = ItemsSource;
if (source != null)
{
foreach (var obj in source)
{
string name = GetDisplayText(obj, DisplayMemberPath);
string pinyinFull = string.Empty;
string initials = string.Empty;
try
{
pinyinFull = PinyinHelper.GetPinyin(name, "").ToLowerInvariant();
initials = PinyinHelper.GetPinyinInitials(name, "").ToLowerInvariant();
}
catch (Exception)
{
// 拼音转换失败时退化为仅名称匹配
}
var item = new ShopFilterItem
{
Source = obj,
DisplayName = name,
GroupName = grouped ? GetDisplayText(obj, GroupByPath) : null,
NameSearch = name.Replace(" ", "").ToLowerInvariant(),
PinyinSearch = pinyinFull,
InitialsSearch = initials
};
item.PropertyChanged += OnItemPropertyChanged;
_allItems.Add(item);
if (grouped)
{
string gname = string.IsNullOrEmpty(item.GroupName) ? "未分组" : item.GroupName;
ShopFilterGroup group;
if (!groupMap.TryGetValue(gname, out group))
{
group = new ShopFilterGroup
{
Name = gname,
CountSuffix = CountSuffix,
IsExpanded = ExpandGroupsByDefault
};
group.PropertyChanged += OnGroupPropertyChanged;
groupMap[gname] = group;
_allGroups.Add(group);
}
group.AllItems.Add(item);
}
else
{
flatGroup.AllItems.Add(item);
}
}
}
_syncing = true;
try { SyncItemStatesFromSelection(); }
finally { _syncing = false; }
ApplyFilter();
RefreshSelectionState();
}
private void ApplyFilter()
{
string keyword = SearchTextBox == null ? string.Empty : (SearchTextBox.Text ?? string.Empty).Trim();
bool searching = keyword.Length > 0;
// 搜索关键词去空格并小写,可同时匹配 中文/全拼/首字母(如 “sh”“shang hai”“上海”)
string kw = keyword.Replace(" ", "").ToLowerInvariant();
_groups.Clear();
_visibleItems.Clear();
foreach (var group in _allGroups)
{
group.Items.Clear();
foreach (var item in group.AllItems)
{
bool match = !searching
|| item.NameSearch.Contains(kw)
|| item.PinyinSearch.Contains(kw)
|| item.InitialsSearch.Contains(kw);
if (match)
{
group.Items.Add(item);
_visibleItems.Add(item);
}
}
if (searching && group.Items.Count > 0)
group.IsExpanded = true;
group.RefreshCountText();
if (!searching || group.Items.Count > 0)
_groups.Add(group);
}
// 高亮项不在可见列表时,重置到第一项
if (_visibleItems.Count == 0)
SetHighlight(null);
else if (!_visibleItems.Contains(_highlightedItem))
SetHighlight(_visibleItems[0]);
}
private void SyncItemStatesFromSelection()
{
var sel = SelectedItems;
foreach (var item in _allItems)
{
bool selected = sel != null && sel.Contains(item.Source);
item.IsSelected = selected;
}
}
#endregion
#region 选择逻辑
private void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(ShopFilterItem.IsSelected)) return;
if (_syncing) return;
var item = (ShopFilterItem)sender;
if (item.IsSelected) AddToSelection(item.Source);
else RemoveFromSelection(item.Source);
RefreshSelectionState();
RaiseSelectionChanged();
}
private void OnGroupPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(ShopFilterGroup.IsChecked)) return;
if (_syncing) return;
var group = (ShopFilterGroup)sender;
bool select = group.IsChecked == true;
_syncing = true;
try
{
foreach (var item in group.AllItems)
item.IsSelected = select;
foreach (var item in group.AllItems)
{
if (select) AddToSelection(item.Source);
else RemoveFromSelection(item.Source);
}
}
finally { _syncing = false; }
RefreshSelectionState();
RaiseSelectionChanged();
}
private void AddToSelection(object source)
{
var sel = SelectedItems;
if (sel == null || source == null) return;
if (!sel.Contains(source)) sel.Add(source);
}
private void RemoveFromSelection(object source)
{
var sel = SelectedItems;
if (sel == null || source == null) return;
if (sel.Contains(source)) sel.Remove(source);
}
/// <summary>全选</summary>
public void SelectAll()
{
_syncing = true;
try
{
foreach (var item in _allItems) item.IsSelected = true;
foreach (var item in _allItems) AddToSelection(item.Source);
}
finally { _syncing = false; }
RefreshSelectionState();
RaiseSelectionChanged();
}
/// <summary>清空选择</summary>
public void ClearSelection()
{
_syncing = true;
try
{
foreach (var item in _allItems) item.IsSelected = false;
if (SelectedItems != null)
{
try { SelectedItems.Clear(); }
catch (NotSupportedException) { }
}
}
finally { _syncing = false; }
RefreshSelectionState();
RaiseSelectionChanged();
}
private void RefreshSelectionState()
{
var sel = SelectedItems;
int total = _allItems.Count;
int count = sel == null ? 0 : sel.Count;
_syncing = true;
try
{
foreach (var group in _allGroups)
{
int selected = group.AllItems.Count(i => i.IsSelected);
group.IsChecked = selected == 0 ? false
: (selected >= group.AllItems.Count ? (bool?)true : null);
}
if (SelectAllCheckBox != null)
{
SelectAllCheckBox.IsChecked = count == 0 ? false
: (total > 0 && count >= total ? true : (bool?)null);
}
}
finally { _syncing = false; }
OnPropertyChanged(nameof(HeaderText));
OnPropertyChanged(nameof(TotalCountText));
OnPropertyChanged(nameof(SelectedCountText));
}
private void RaiseSelectionChanged()
{
RaiseEvent(new RoutedEventArgs(SelectionChangedEvent));
}
/// <summary>确定:关闭下拉并触发 Confirmed</summary>
private void Confirm()
{
DropDownToggle.IsChecked = false;
RaiseEvent(new RoutedEventArgs(ConfirmedEvent));
}
/// <summary>取消:还原打开前的选择,关闭下拉并触发 Cancelled</summary>
private void Cancel()
{
_syncing = true;
try
{
var sel = SelectedItems;
if (sel != null)
{
try { sel.Clear(); }
catch (NotSupportedException) { }
if (_openedSnapshot != null)
{
foreach (var obj in _openedSnapshot)
sel.Add(obj);
}
}
}
finally { _syncing = false; }
RefreshSelectionState();
RaiseSelectionChanged();
DropDownToggle.IsChecked = false;
RaiseEvent(new RoutedEventArgs(CancelledEvent));
}
#endregion
#region 键盘
/// <summary>下拉打开时:↑/↓ 选择,空格 选中/取消,Enter 确定,Esc 取消</summary>
private void DropDownRoot_PreviewKeyDown(object sender, KeyEventArgs e)
{
// 输入法合成中(如拼音输入法)时,Enter/Esc 交给输入法处理,避免误触发确定/取消
if ((e.Key == Key.Enter || e.Key == Key.Escape) && e.ImeProcessedKey != Key.None)
return;
switch (e.Key)
{
case Key.Escape:
e.Handled = true;
Cancel();
break;
case Key.Enter:
e.Handled = true;
Confirm();
break;
case Key.Down:
e.Handled = true;
MoveHighlight(1);
break;
case Key.Up:
e.Handled = true;
MoveHighlight(-1);
break;
case Key.Space:
if (_highlightedItem != null)
{
e.Handled = true;
_highlightedItem.IsSelected = !_highlightedItem.IsSelected;
}
break;
}
}
/// <summary>下拉关闭时按 ↑/↓/Enter/空格 打开下拉</summary>
private void Root_KeyDown(object sender, KeyEventArgs e)
{
if (DropDownToggle.IsChecked == true) return;
if (e.Key == Key.Down || e.Key == Key.Up || e.Key == Key.Enter || e.Key == Key.Space)
{
e.Handled = true;
DropDownToggle.IsChecked = true;
}
}
private void SetHighlight(ShopFilterItem item)
{
if (ReferenceEquals(_highlightedItem, item)) return;
if (_highlightedItem != null) _highlightedItem.IsHighlighted = false;
_highlightedItem = item;
if (_highlightedItem != null)
{
_highlightedItem.IsHighlighted = true;
// 高亮项所在分组若被折叠则展开
foreach (var group in _allGroups)
{
if (group.AllItems.Contains(_highlightedItem) && !group.IsExpanded)
{
group.IsExpanded = true;
break;
}
}
BringHighlightedIntoView();
}
}
private void MoveHighlight(int delta)
{
if (_visibleItems.Count == 0) return;
int idx;
if (_highlightedItem == null)
{
idx = delta >= 0 ? 0 : _visibleItems.Count - 1;
}
else
{
idx = _visibleItems.IndexOf(_highlightedItem);
if (idx < 0) idx = delta >= 0 ? 0 : _visibleItems.Count - 1;
else idx = Math.Max(0, Math.Min(_visibleItems.Count - 1, idx + delta));
}
SetHighlight(_visibleItems[idx]);
}
private void BringHighlightedIntoView()
{
if (_highlightedItem == null) return;
var check = FindVisualChild<CheckBox>(DropDownRoot, cb => cb.DataContext == _highlightedItem);
if (check != null) check.BringIntoView();
}
private static T FindVisualChild<T>(DependencyObject parent, Func<T, bool> predicate) where T : DependencyObject
{
int count = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T t && predicate(t)) return t;
var result = FindVisualChild(child, predicate);
if (result != null) return result;
}
return null;
}
#endregion
#region 事件处理
private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ApplyFilter();
}
private void SelectAllCheckBox_Click(object sender, RoutedEventArgs e)
{
var cb = (CheckBox)sender;
if (cb.IsChecked == true) SelectAll();
else ClearSelection();
}
/// <summary>鼠标点击某项时,把键盘高亮同步到该项</summary>
private void ItemCheckBox_Click(object sender, RoutedEventArgs e)
{
var item = (sender as FrameworkElement)?.DataContext as ShopFilterItem;
if (item != null) SetHighlight(item);
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
ClearSelection();
}
private void SelectAllButton_Click(object sender, RoutedEventArgs e)
{
SelectAll();
}
private void ConfirmButton_Click(object sender, RoutedEventArgs e)
{
Confirm();
}
private void GroupHeader_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var group = (sender as FrameworkElement)?.DataContext as ShopFilterGroup;
if (group != null) group.IsExpanded = !group.IsExpanded;
}
private void DropDownPopup_Opened(object sender, EventArgs e)
{
// 下拉宽度不小于按钮宽度
if (DropDownRoot != null)
DropDownRoot.MinWidth = Math.Max(300, RootGrid.ActualWidth);
// 记录打开时的选中快照,Esc 取消时还原
_openedSnapshot = SelectedItems == null ? new List<object>() : SelectedItems.Cast<object>().ToList();
// 每次打开清空搜索,显示完整列表
if (SearchTextBox != null)
SearchTextBox.Text = string.Empty;
// 重新同步外部对 SelectedItems 的修改
OnSelectionContentChanged();
// 高亮第一项
if (_visibleItems.Count > 0)
SetHighlight(_visibleItems[0]);
if (SearchTextBox != null && IsSearchable)
{
SearchTextBox.Focus();
SearchTextBox.SelectAll();
}
else
{
DropDownRoot.Focus();
}
}
private void OnSelectionContentChanged()
{
if (_syncing) return;
_syncing = true;
try { SyncItemStatesFromSelection(); }
finally { _syncing = false; }
RefreshSelectionState();
}
#endregion
#region 反射取值
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _propertyCache =
new Dictionary<Type, Dictionary<string, PropertyInfo>>();
private static readonly object _cacheLock = new object();
private static PropertyInfo FindProperty(Type type, string path)
{
lock (_cacheLock)
{
Dictionary<string, PropertyInfo> map;
if (!_propertyCache.TryGetValue(type, out map))
{
map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
_propertyCache[type] = map;
}
PropertyInfo cached;
if (map.TryGetValue(path, out cached)) return cached;
PropertyInfo pi = null;
Type current = type;
foreach (var part in path.Split('.'))
{
pi = current.GetProperty(part, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (pi == null) break;
current = pi.PropertyType;
}
map[path] = pi;
return pi;
}
}
private static string GetDisplayText(object item, string path)
{
if (item == null) return string.Empty;
if (string.IsNullOrEmpty(path))
return Convert.ToString(item, CultureInfo.CurrentCulture);
var pi = FindProperty(item.GetType(), path);
if (pi == null) return string.Empty;
var value = pi.GetValue(item);
return value == null ? string.Empty : Convert.ToString(value, CultureInfo.CurrentCulture);
}
#endregion
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
@@ -0,0 +1,146 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace _29WxOrderWpf.Ctrls.Commons
{
/// <summary>
/// 商铺筛选下拉 - 单项视图模型(包装原始数据项,附加显示名/分组名/选中状态/搜索键/高亮)。
/// 由 <see cref="ShopFilterComboBox"/> 内部维护,不直接使用。
/// </summary>
public class ShopFilterItem : INotifyPropertyChanged
{
private bool _isSelected;
private bool _isHighlighted;
/// <summary>原始数据项(ItemsSource 中的元素)</summary>
public object Source { get; set; }
/// <summary>显示名称(由 DisplayMemberPath 解析)</summary>
public string DisplayName { get; set; }
/// <summary>所属分组名称(由 GroupByPath 解析,未分组模式下为 null)</summary>
public string GroupName { get; set; }
/// <summary>搜索键:名称(去空格小写,支持中文片段匹配)</summary>
public string NameSearch { get; set; }
/// <summary>搜索键:完整拼音(无空格小写,如“上海旗舰店”=“shanghaiqijiandian”)</summary>
public string PinyinSearch { get; set; }
/// <summary>搜索键:拼音首字母(小写,如“上海旗舰店”=“shqjd”)</summary>
public string InitialsSearch { get; set; }
/// <summary>是否选中</summary>
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected == value) return;
_isSelected = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsSelected)));
}
}
/// <summary>是否高亮(键盘上下选择时)</summary>
public bool IsHighlighted
{
get { return _isHighlighted; }
set
{
if (_isHighlighted == value) return;
_isHighlighted = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsHighlighted)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
/// <summary>
/// 商铺筛选下拉 - 分组视图模型(分组头:展开/收起、全选复选框、数量)。
/// 由 <see cref="ShopFilterComboBox"/> 内部维护,不直接使用。
/// </summary>
public class ShopFilterGroup : INotifyPropertyChanged
{
private bool _isExpanded;
private bool? _isChecked;
private string _countSuffix = "家";
public ShopFilterGroup()
{
_isExpanded = true;
}
/// <summary>分组名称;空字符串表示未分组(隐藏分组头)</summary>
public string Name { get; set; }
/// <summary>分组内全部原始项(未过滤,用于计数与全选/清空)</summary>
public List<ShopFilterItem> AllItems { get; } = new List<ShopFilterItem>();
/// <summary>分组内当前显示的项(受搜索过滤影响)</summary>
public ObservableCollection<ShopFilterItem> Items { get; } = new ObservableCollection<ShopFilterItem>();
/// <summary>是否展开</summary>
public bool IsExpanded
{
get { return _isExpanded; }
set
{
if (_isExpanded == value) return;
_isExpanded = value;
Raise(nameof(IsExpanded));
}
}
/// <summary>分组头复选框状态:true=全选,false=全不选,null=部分选中</summary>
public bool? IsChecked
{
get { return _isChecked; }
set
{
if (_isChecked == value) return;
_isChecked = value;
Raise(nameof(IsChecked));
}
}
/// <summary>数量单位(如“家”)</summary>
public string CountSuffix
{
get { return _countSuffix; }
set
{
if (_countSuffix == value) return;
_countSuffix = value;
Raise(nameof(CountText));
}
}
/// <summary>是否显示分组头(未分组时隐藏)</summary>
public bool IsHeaderVisible
{
get { return !string.IsNullOrEmpty(Name); }
}
/// <summary>分组数量文本(如“12家”)</summary>
public string CountText
{
get { return Items.Count + CountSuffix; }
}
/// <summary>过滤后刷新数量文本</summary>
public void RefreshCountText()
{
Raise(nameof(CountText));
}
public event PropertyChangedEventHandler PropertyChanged;
private void Raise(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
@@ -15,8 +15,8 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Models
/// <summary>结束时间</summary>
public DateTime EndDate { get; set; }
/// <summary>店铺 shop_id(B.shop_id),空/Null 表示全部店铺</summary>
public string ShopKey { get; set; }
/// <summary>选中的店铺 app_key 列表;空/Null 表示全部店铺</summary>
public List<string> ShopKeys { get; set; }
}
/// <summary>
@@ -2,10 +2,12 @@
x:Class="_29WxOrderWpf.Ctrls.Statistics.RevenueStatisticsSearchBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:_29WxOrderWpf.Ctrls.Commons"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:_29WxOrderWpf.Ctrls.Statistics.ViewModels"
d:DataContext="{d:DesignInstance Type=vm:ShopRevenueStatisticsViewModel,IsDesignTimeCreatable=True}"
d:DataContext="{d:DesignInstance Type=vm:ShopRevenueStatisticsViewModel,
IsDesignTimeCreatable=True}"
mc:Ignorable="d">
<UserControl.Resources>
<!-- 日期只允许从日历选择,禁止手工输入 -->
@@ -42,21 +44,23 @@
FontSize="14"
Foreground="#666666"
Text="时间" />
<ComboBox IsEnabled="False"
<ComboBox
Width="110"
Height="32"
VerticalContentAlignment="Center"
DisplayMemberPath="Text"
IsReadOnly="True"
BorderThickness="1"
ItemsSource="{Binding TimeRangeOptions}"
SelectedItem="{Binding SelectedTimeRange, Mode=TwoWay}"
Style="{StaticResource BaseComboBoxStyle}" />
Style="{StaticResource RoundedComboBox}" />
<TextBlock
Margin="14,0,6,0"
VerticalAlignment="Center"
FontSize="14"
Foreground="#666666"
Text="日期" />
<DatePicker
<DatePicker BorderBrush="{StaticResource pageColorBrush}"
Height="32"
VerticalContentAlignment="Center"
SelectedDate="{Binding StartDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
@@ -66,7 +70,7 @@
FontSize="14"
Foreground="#666666"
Text="~" />
<DatePicker
<DatePicker BorderBrush="{StaticResource pageColorBrush}"
Height="32"
VerticalContentAlignment="Center"
SelectedDate="{Binding EndDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
@@ -76,14 +80,21 @@
FontSize="14"
Foreground="#666666"
Text="店铺" />
<ComboBox IsEnabled="False"
<c:ShopFilterComboBox
Width="130"
Height="32"
DisplayMemberPath="ShopName"
IsGrouped="True"
ItemsSource="{Binding ShopOptions}"
SelectedItems="{Binding SelectedShops}" />
<!--<ComboBox IsEnabled="False"
Width="130"
Height="32"
VerticalContentAlignment="Center"
DisplayMemberPath="ShopName"
ItemsSource="{Binding ShopOptions}"
SelectedItem="{Binding SelectedShop, Mode=TwoWay}"
Style="{StaticResource BaseComboBoxStyle}" />
Style="{StaticResource BaseComboBoxStyle}" />-->
<Button
Height="32"
Margin="18,0,0,0"
@@ -431,8 +431,8 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Services
}
}
// 3. 按天从缓存拼装完整范围,再按所选店铺过滤(ShopKey 为空 = 全部店铺)
return FilterByShop(GetCachedRows(startDay, endDay), query.ShopKey);
// 3. 按天从缓存拼装完整范围,再按所选店铺过滤(ShopKeys 为空 = 全部店铺)
return FilterByShop(GetCachedRows(startDay, endDay), query.ShopKeys);
}
/// <summary>
@@ -477,21 +477,24 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Services
return result;
}
/// <summary>按所选店铺过滤明细:ShopKey 为空返回全部;否则按店铺名(ShopName)精确匹配。</summary>
private static List<ShopRevenueStatisticsRow> FilterByShop(List<ShopRevenueStatisticsRow> rows, string shopKey)
/// <summary>按所选店铺过滤明细:ShopKeys 为空/Null 返回全部;否则按店铺名(ShopName)精确匹配。</summary>
private static List<ShopRevenueStatisticsRow> FilterByShop(List<ShopRevenueStatisticsRow> rows, List<string> shopKeys)
{
if (rows == null)
return new List<ShopRevenueStatisticsRow>();
if (string.IsNullOrEmpty(shopKey))
if (shopKeys == null || shopKeys.Count == 0)
return new List<ShopRevenueStatisticsRow>(rows);
var shop = GetShopOptions().FirstOrDefault(a => a.AppKey == shopKey);
if (shop == null || string.IsNullOrEmpty(shop.ShopName))
var shops = GetShopOptions()
.Where(a => shopKeys.Contains(a.AppKey))
.Where(a => !string.IsNullOrEmpty(a.ShopName))
.ToList();
if (shops.Count == 0)
return new List<ShopRevenueStatisticsRow>();
return rows
.Where(r => string.Equals(r.ShopName, shop.ShopName, StringComparison.OrdinalIgnoreCase))
.Where(r => shops.Any(s => string.Equals(r.ShopName, s.ShopName, StringComparison.OrdinalIgnoreCase)))
.ToList();
}
@@ -20,7 +20,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
public class PeriodRevenueStatisticsViewModel : PropertyNotifyObject
{
/// <summary>每页行数</summary>
private const int PageSize = 20;
private const int PageSize = 50;
private readonly IShopRevenueStatisticsService _service;
private readonly PeriodStatisticType _periodType;
@@ -29,7 +29,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
private readonly DelegateCommand _nextPageCommand;
private readonly DelegateCommand _lastPageCommand;
private ShopOption _selectedShop;
private ObservableCollection<ShopOption> _selectedShops;
private ShopRevenueSummary _summary;
private ObservableCollection<ShopPeriodStatisticsItem> _statistics;
private List<ShopPeriodStatisticsItem> _allItems = new List<ShopPeriodStatisticsItem>();
@@ -192,17 +192,17 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
set { this.SetValue(x => x.EndDate, value); }
}
/// <summary>店铺选项(含“全部店铺”)</summary>
/// <summary>店铺选项(“全部店铺”由多选控件“全部商铺”表示)</summary>
public ObservableCollection<ShopOption> ShopOptions { get; }
/// <summary>选中的店铺</summary>
public ShopOption SelectedShop
/// <summary>选中的店铺(多选,绑定 ShopFilterComboBox.SelectedItems)</summary>
public ObservableCollection<ShopOption> SelectedShops
{
get { return _selectedShop; }
get { return _selectedShops; }
set
{
_selectedShop = value;
OnPropertyChanged(nameof(SelectedShop));
_selectedShops = value;
OnPropertyChanged(nameof(SelectedShops));
}
}
@@ -378,12 +378,11 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
{
try
{
// 店铺选项
ShopOptions.Add(new ShopOption { AppKey = string.Empty, ShopName = "全部店铺" });
// 店铺选项(全部店铺由多选控件“全部商铺”表示,不再额外加入“全部店铺”项)
var shops = await _service.GetShopOptionsAsync();
foreach (var shop in shops)
ShopOptions.Add(shop);
SelectedShop = ShopOptions.FirstOrDefault();
SelectedShops = new ObservableCollection<ShopOption>(ShopOptions);
// 默认时间范围
SelectedTimeRange = TimeRangeOptions.FirstOrDefault(t => t.Value == GetDefaultTimeRangeValue(_periodType));
@@ -477,6 +476,23 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
}
}
/// <summary>根据选中店铺生成查询店铺 key 列表:未选/全选/选中“全部店铺”时返回空列表(表示全部店铺)</summary>
private List<string> BuildSelectedShopKeys()
{
var selected = SelectedShops;
if (selected == null || selected.Count == 0)
return new List<string>();
var keys = selected.Select(s => s == null ? string.Empty : s.AppKey).ToList();
if (keys.Any(string.IsNullOrEmpty))
return new List<string>();
if (selected.Count >= ShopOptions.Count)
return new List<string>();
return keys;
}
/// <summary>执行查询,刷新周期统计表格并回到第一页</summary>
private async Task LoadAsync()
{
@@ -494,7 +510,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
{
StartDate = StartDate,
EndDate = EndDate,
ShopKey = SelectedShop == null ? string.Empty : SelectedShop.AppKey,
ShopKeys = BuildSelectedShopKeys(),
};
var table = await _service.GetPeriodStatisticsAsync(query, _periodType);
@@ -518,7 +534,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
/// <summary>重置查询条件并重新加载</summary>
private async void Reset()
{
SelectedShop = ShopOptions.FirstOrDefault();
SelectedShops = new ObservableCollection<ShopOption>(ShopOptions);
SelectedTimeRange = TimeRangeOptions.FirstOrDefault(t => t.Value == GetDefaultTimeRangeValue(_periodType));
ApplyTimeRange();
await LoadAsync();
@@ -25,7 +25,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
private ObservableCollection<RevenueTrendPoint> _trendData;
private ObservableCollection<ShopSalesProportionItem> _shopProportionData;
private ObservableCollection<ShopStatisticsItem> _shopStatistics;
private ShopOption _selectedShop;
private ObservableCollection<ShopOption> _selectedShops;
private string _selectedPlatform;
public ShopRevenueStatisticsViewModel()
@@ -92,17 +92,17 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
set { this.SetValue(x => x.EndDate, value); }
}
/// <summary>店铺选项(含“全部店铺”)</summary>
/// <summary>店铺选项(“全部店铺”由多选控件“全部商铺”表示)</summary>
public ObservableCollection<ShopOption> ShopOptions { get; }
/// <summary>选中的店铺</summary>
public ShopOption SelectedShop
public ObservableCollection<ShopOption> SelectedShops
{
get { return _selectedShop; }
get { return _selectedShops; }
set
{
_selectedShop = value;
OnPropertyChanged(nameof(SelectedShop));
_selectedShops = value;
OnPropertyChanged(nameof(SelectedShops));
}
}
@@ -179,12 +179,11 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
{
try
{
// 店铺选项
ShopOptions.Add(new ShopOption { AppKey = string.Empty, ShopName = "全部店铺" });
// 店铺选项(全部店铺由多选控件“全部商铺”表示,不再额外加入“全部店铺”项)
var shops = await _service.GetShopOptionsAsync();
foreach (var shop in shops)
ShopOptions.Add(shop);
SelectedShop = ShopOptions.FirstOrDefault();
SelectedShops = new ObservableCollection<ShopOption>(ShopOptions);
// 默认时间范围:本月
SelectedTimeRange = TimeRangeOptions.FirstOrDefault(t => t.Value == "month");
@@ -233,6 +232,23 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
}
}
/// <summary>根据选中店铺生成查询店铺 key 列表:未选/全选/选中“全部店铺”时返回空列表(表示全部店铺)</summary>
private List<string> BuildSelectedShopKeys()
{
var selected = SelectedShops;
if (selected == null || selected.Count == 0)
return new List<string>();
var keys = selected.Select(s => s == null ? string.Empty : s.AppKey).ToList();
if (keys.Any(string.IsNullOrEmpty))
return new List<string>();
if (selected.Count >= ShopOptions.Count)
return new List<string>();
return keys;
}
/// <summary>执行查询,刷新页面所有统计数据</summary>
private async Task LoadAsync()
{
@@ -250,7 +266,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
{
StartDate = StartDate,
EndDate = EndDate,
ShopKey = SelectedShop == null ? string.Empty : SelectedShop.AppKey,
ShopKeys = BuildSelectedShopKeys(),
};
Summary = await _service.GetSummaryAsync(query);
@@ -277,7 +293,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
/// <summary>重置查询条件并重新加载</summary>
private async void Reset()
{
SelectedShop = ShopOptions.FirstOrDefault();
SelectedShops = new ObservableCollection<ShopOption>(ShopOptions);
SelectedTimeRange = TimeRangeOptions.FirstOrDefault(t => t.Value == "month");
ApplyTimeRange();
await LoadAsync();