WPFTemplateLib — WPF 帮助类库

WPFTemplateLib — WPF 帮助类库

目录 显示

WPFTemplateLibWPF 帮助类库

简介

WPFTemplateLib 是由 独立观察员(DLGCY) 收集、整合、开发和维护的 WPF 帮助类库,旨在简化 WPF 桌面应用开发,提供MVVM 基础设施、丰富的自定义控件、大量开箱即用的转换器、可绑定的附加属性与行为、样式主题系统、配置管理等全套解决方案。

NuGet Gitee .NET .NET


快速开始

安装

Install-Package WPFTemplateLib

版本兼容性

目标框架 说明
net472 .NET Framework 4.7.2
net6.0-windows .NET 6.0(Windows)

XAML 命名空间引入

xmlns:lib="https://gitee.com/dlgcy/WPFTemplateLib"

依赖包

项目依赖 13 个 NuGet 包,包括 CalcBinding(表达式绑定)、MahApps.Metro(Metro 风格控件)、Microsoft.Xaml.Behaviors.Wpf(行为支持)、Extended.Wpf.Toolkit(扩展控件)、Newtonsoft.Json(JSON 序列化)、SharpVectors.Wpf(SVG 支持)等。

资源字典引入

 App.xaml 中引入核心资源字典:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- 转换器 -->
            <ResourceDictionary Source="pack://application:,,,/WPFTemplateLib;component/WpfConverters/ConverterDictionary.xaml"/>
            <!-- 样式 -->
            <ResourceDictionary Source="pack://application:,,,/WPFTemplateLib;component/Styles/StyleDictionary.xaml"/>
            <!-- 默认主题样式 -->
            <ResourceDictionary Source="pack://application:,,,/WPFTemplateLib;component/Themes/DefaultThemeDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

功能模块详解

1. MVVM 基础支持

库提供完整的 MVVM 基类体系,继承层次如下:

ObservableObject  →  SimpleBindableBase  →  NotifyDataErrorObject  →  ViewModelBase

1.1 ObservableObject(命名空间:WPFTemplateLib.Mvvm

实现 INotifyPropertyChanged  INotifyPropertyChanging,是所有 MVVM 类的根基类。

成员 说明
OnPropertyChanged([CallerMemberName] string propertyName = null) 触发属性变更通知
OnPropertyChanging([CallerMemberName] string propertyName = null) 触发属性将要变更通知
SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) 值不同时设置并通知
SetPropertyWithoutCompare<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) 不比较直接设置并通知
PropertyChangedHandle(string propertyName) 虚方法,子类重写响应属性变化
PropertySetIntentionHandle<T>(ref T prevValue, ref T newValue, string propertyName) 虚方法,无论值是否变化都会调用
public class MyModel : ObservableObject
{
    private string _name;
    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }
}

1.2 SimpleBindableBase

使用 PropertyChanged.Fody 包([AddINotifyPropertyChangedInterface] 特性)自动编织属性变更通知代码。普通公共自动属性无需手动调用 SetProperty

注意:使用的项目中仍需安装 PropertyChanged.Fody 包。

public class MyBindable : SimpleBindableBase
{
    public string Name { get; set; }   // 自动支持属性变更通知
    public int Age { get; set; }        // 自动支持属性变更通知
}

1.3 NotifyDataErrorObject

实现 INotifyDataErrorInfo,提供数据验证错误通知功能。

成员 说明
HasErrors 是否存在任何错误(只读)
GetErrors(string propertyName) 获取指定属性的错误列表(参数为空获取所有)
IsContainErrors(string propertyName) 判断指定属性是否包含错误
IsContainErrors(List<string> propertyNameList) 判断指定属性列表中是否有任意属性包含错误
ValidateBlank(object value, string errMsg, [CallerMemberName] string propertyName) 验证是否为空,返回 true 表示不为空
ErrorsChanged 错误变更事件
public class MyValidatable : NotifyDataErrorObject
{
    private string _name;
    public string Name
    {
        get => _name;
        set
        {
            SetProperty(ref _name, value);
            ValidateBlank(value, "名称不能为空");  // 触发验证
        }
    }
}
<!-- 界面绑定错误提示 -->
<TextBox Text="{Binding Name, ValidatesOnNotifyDataErrors=True}" />

1.4 ViewModelBase

ViewModel 基类,继承自 NotifyDataErrorObject,提供程序运行消息输出、Toast 气泡弹窗、窗口载入处理等内置功能。

消息输出:

成员 说明
Info (string) 信息区绑定内容
ShowInfo(string info, bool isAddBlankLine = false) 追加普通信息(带时间戳)
ShowInfoUc(string info, bool isAddBlankLine = false) 使用 UC_InfoRegion 时的信息输出(Dispatcher 线程安全)
IsSetConsoleOutput (bool) 是否将 Console 输出重定向到信息区

Toast 气泡弹窗命令:

成员 说明
ToastToWindowCmd (RelayCommand<List<object>>) 窗口中间弹窗命令
ToastToScreenCmd (RelayCommand<string>) 屏幕中间弹窗命令
ToastToScreen(msg, icon, ms, color) 屏幕中间弹窗方法
ToastToScreenWarning(msg, ms) 屏幕中间警告弹窗(橙色图标)
ToastToScreenError(msg, ms) 屏幕中间错误弹窗(红色图标)
ToastToWindow(msg, win, icon, ms, color) 窗口中间弹窗方法

窗口载入:

成员 说明
LoadedCmd (ICommand) 绑定到窗口 Loaded 事件
OnLoaded(bool isFirst) 虚方法,子类重写处理载入(参数标识是否首次)
public class MainViewModel : ViewModelBase
{
    protected override void OnLoaded(bool isFirst)
    {
        if (isFirst)
        {
            ToastToScreen("系统初始化完成", ToastIcons.Information, 3000);
        }
    }
}
<!-- 绑定 Loaded 事件 -->
<b:Interaction.Triggers>
    <b:EventTrigger EventName="Loaded">
        <b:InvokeCommandAction Command="{Binding LoadedCmd}" />
    </b:EventTrigger>
</b:Interaction.Triggers>

1.5 RelayCommand(命名空间:WPFTemplateLib.WpfHelpers

支持同步和异步执行、CanExecute 条件判断、异步防重入(_isExecutingAsync 标志在异步执行期间禁用按钮防止重复点击)、手动触发 CanExecute 重新计算。

构造函数(非泛型版 RelayCommand):

new RelayCommand(Predicate<object> canExecute, Action<object> execute)
new RelayCommand(Predicate<object> canExecute, Func<object, Task> executeAsync)
new RelayCommand(Action<object> execute)
new RelayCommand(Action executeWithoutPara)  // 无参数简化版
new RelayCommand(Func<object, Task> executeAsync)

构造函数(泛型版 RelayCommand<T>):

new RelayCommand<T>(Predicate<T> canExecute, Action<T> execute)
new RelayCommand<T>(Predicate<T> canExecute, Func<T, Task> executeAsync)
new RelayCommand<T>(Action<T> execute)
new RelayCommand<T>(Func<T, Task> executeAsync)

公共方法:

方法 说明
RaiseCanExecuteChanged() 手动触发 CanExecute 重新计算
CanExecute(object parameter) 判断命令是否可执行
Execute(object parameter) 执行命令
// 同步命令
public ICommand SaveCommand => new RelayCommand(o => 
{
    SaveData();
});

// 异步命令 + 条件判断
public ICommand LoadCommand => new RelayCommand(
    o => !IsLoading,                         // canExecute
    async o => await LoadDataAsync()         // executeAsync
);

// 无参数简化
public ICommand RefreshCommand => new RelayCommand(() => Refresh());

2. 样式(Style)

2.1 命名规范

前缀 说明
LibSty 库自定义样式
SysSty 系统内置简单样式
LibTpl 库自定义控件模板
SysTpl 系统内置控件模板

2.2 关键默认样式 Key

样式 Key 目标类型 基础样式
LibSty.Button.Default Button LibSty.WpfUi.Button.Ele.Primary
LibSty.CheckBox.Default CheckBox LibSty.WpfUi.CheckBox.Basic
LibSty.ComboBox.Default ComboBox LibSty.WpfUi.ComboBox.Primary
LibSty.Expander.Default Expander MahApps.Styles.Expander
LibSty.GroupBox.Default GroupBox MahApps.Styles.GroupBox.Fix
LibSty.RadioButton.Default RadioButton LibSty.WpfUi.RadioButton.Basic
LibSty.ScrollBar.Default ScrollBar LibSty.ScrollBar
LibSty.ScrollViewer.Default ScrollViewer LibSty.ScrollViewer
LibSty.ToggleButton.Default ToggleButton MahApps.Styles.ToggleButton.Flat
LibSty.TreeView.Default TreeView MahApps.Styles.TreeView
LibSty.TreeViewItem.Default TreeViewItem MahApps.Styles.TreeViewItem.Fix
LibSty.TextBlock.Default TextBlock SysSty.TextBlock

2.3 StyleDictionary.xaml 合并的子字典(22 个)

StyleDictionary.xaml 合并了以下子字典文件:

DictionaryCommonDictionaryBorderDictionaryButtonDictionaryCalendarDictionaryCheckBoxDictionaryComboBoxDictionaryContentControlDictionaryDataGridDictionaryLabelDictionaryListBoxDictionaryListViewDictionaryPathDictionaryProgressBarDictionaryRadioButtonDictionaryScrollDictionarySeparatorDictionaryTabControlDictionaryTextBlockDictionaryTextBoxDictionaryToggleButtonDictionaryUserControlsDictionaryCustomControlDictionaryMahApps


3. 主题(Theme)

库的 Generic.xaml 提供了完整的默认控件样式,同时支持颜色主题切换。颜色主题文件位于 Themes/ 目录:

主题文件 说明
Light.xaml 浅色主题(默认)
Light.Blue.xaml 浅色蓝色主题
Light.Green.xaml 浅色绿色主题
FruitVent/ FruitVent 设计风格主题目录

主题切换通过 DefaultThemeDictionary.xaml 控制,将 13 种控件类型设置到对应的默认样式。在 App.xaml 中引入 DefaultThemeDictionary.xaml 即可应用主题:

<ResourceDictionary Source="pack://application:,,,/WPFTemplateLib;component/Themes/DefaultThemeDictionary.xaml"/>

4. 转换器(Converter)

库提供了 70+ 个开箱即用的转换器,定义在 ConverterDictionary.xaml 中。在 App.xaml 中引入即可全局使用:

<ResourceDictionary Source="pack://application:,,,/WPFTemplateLib;component/WpfConverters/ConverterDictionary.xaml"/>

4.1 布尔/可见性类

Key 说明
VisibleConverter bool 为 true 显示
CollapsedConverter bool 为 true 隐藏
BoolToVisibilityConverter 布尔值转 Visibility
TrueToVisibleConverter true → Visible
TrueToCollapsedConverter true → Collapsed
TrueToHiddenConverter true → Hidden
VisibleCollapsedSwitchConverter Visible ↔ Collapsed 切换
BoolReverseConverter 反转布尔值
BoolToNullableBoolConverter bool 转 bool?(支持回转)

4.2 条件判断类

Key 说明
ObjectConverter 单值通用转换器(参数规则:比较值1|比较值2:true返回值:false返回值
MultiObjectConverter 多值通用转换器
IsEqualToParaConverter Equals 方法比较
IsToStringEqualToParaConverter ToString 字符串相等比较
StringContainsConverter 字符串包含判断
ObjectIsNullConverter 判断对象是否为 null
ObjectIsNotNullConverter 判断对象是否不为 null
IsNullOrWhitespaceConverter 字符串为空判断
IsNotNullOrWhitespaceConverter 字符串非空判断
IsNullOrEmptyObjectConverter 对象为空判断

4.3 可见性联动类

Key 说明
ValueToVisibleConverter 值匹配参数时显示
ValueToCollapsedConverter 值匹配参数时隐藏
StringNotEmptyToVisibleConverter 字符串非空显示
ObjectNotNullToVisibleConverter 对象不为 null 显示
CollectionNotEmptyToVisibleConverter 集合不为空显示

4.4 数值运算类

Key 说明
DivideConverter 等分转换器
ReduceDoubleConverter 减少转换器(值 – 参数)
AddDoubleConverter 增加转换器(值 + 参数)
MultiplyDoubleConverter 相乘转换器(值 × 参数)
DivideDoubleConverter 相除转换器(值 ÷ 参数)
ParaDivideValueDoubleConverter 参数作被除数的相除
ModuloDoubleConverter 取模转换器
ValueToAbsConverter 取绝对值
DoubleToGridLengthConverter double 转 GridLength

4.5 数值比较类

Key CompareAction 说明
GreaterThanParaNumberConverter GreaterThan 大于参数
GreaterThanOrEqualParaNumberConverter GreaterThanOrEqual 大于等于参数
EqualParaNumberConverter Equal 等于参数
LessThanOrEqualParaNumberConverter LessThanOrEqual 小于等于参数
LessThanParaNumberConverter LessThan 小于参数

4.6 列表/集合类

Key 说明
GetCollectionLengthConverter 获取集合长度
ListContainsElementMultiConverter 判断列表是否包含元素(多值)
MultiToListObjectConverter 多重绑定转为 List<object>

4.7 多值逻辑判断类

Key 说明
IsAllTrueConverter 是否全为真
IsAllFalseConverter 是否全为假
IsContainsTrueConverter 是否包含真
IsAllStrEqualMultiConverter 字符串形式是否全部相等
IsHeadOfListMultiConverter 是否在列表头部
IsTailOfListMultiConverter 是否在列表尾部

4.8 多值结果类

Key JudgeType 说明
JudgeListReturnParaValueMultiConverter AllTrue 判断并返回指定值
AllTrueReturnParaValueMultiConverter AllTrue 全真返回指定值
AllFalseReturnParaValueMultiConverter AllFalse 全假返回指定值
ContainsTrueReturnParaValueMultiConverter ContainTrue 包含真返回指定值
JoinStringsConverter 连接字符串
ReferenceValueToRealValueMultiConverter 参考值转实际值

4.9 数字范围判断类

Key 说明
IsNumberInRangeMultiConverter 判断数字是否在指定范围内(多值绑定版)
IsHeadOfListConverter / IsTailOfListConverter 判断是否在列表头/尾

4.10 图片/资源类

Key 说明
ObjectToImageSourceConverter object 转图片资源
AllTypeToImageSourceConverter 多类型转图片资源(string/Stream/Uri/byte[])
BitmapToImageSourceConverter Bitmap 转 ImageSource
StringToImageSourceConverter 字符串(文件名)转图片(参数为格式化字符串)
StringToUriConverter 字符串转 Uri

4.11 颜色/画刷类

Key 说明
StringColorToBrushConverter 字符串颜色转 SolidColorBrush
MediaColorToBrushConverter Media.Color → SolidColorBrush
BrushToMediaColorConverter SolidColorBrush → Media.Color

4.12 字符串处理类

Key 说明
ToStringConverter 转字符串
StringFormatConverter 字符串格式化(支持 IsEmptyNotApplyFormat
TrueFalseConverter “True”/”False” 字符串 → bool
EmptyToParaConverter 空值显示为参数指定值
ObjectToJsonConverter 对象转 JSON(支持 IsIndented 格式化)
ParaToUpperOrLowerByValueConverter 参数大小写转换
ParaToUpperWhileValueIsTrueConverter value 为 true 时参数转大写
ParaToLowerWhileValueIsTrueConverter value 为 true 时参数转小写

4.13 枚举/键值映射类

Key 说明
GetEnumDescriptionConverter 获取枚举 Description
ShowEnumInfoConverter 显示枚举信息
EnumToStrInParaConverter 枚举转参数字符串
BindAsKeyFindValueInParaConverter 绑定值作 Key 在参数中找 Value
BindAsKeyFindValueInPropertyConverter 绑定值作 Key 在属性中找 Value

4.14 Grid 布局类

Key 说明
BoolToGridLengthConverter bool 转 GridLength
BoolInvertedToGridLengthConverter 反相 bool 转 GridLength
BoolToGridLengthConverterV2 bool 转 GridLength(属性版,TrueValue/FalseValue

4.15 其他

Key 说明
ObjectToIntConverter object 转 int(失败返回 0)
DataGridRowToNoConverter DataGridRow 转行号
PercentValueToCircleValueConverter 百分比值转圆周值(0-100 → 0-360)
FloatToScienceConverter 浮点数转科学计数法
InputScopeNameValueConverter InputScopeNameValue → InputScope
StringToCornerRadiusConverter 字符串转 CornerRadius
StringToPathGeometry XAML 字符串转 Geometry
GetFileNameConverter 获取文件名
GetFileNameWithoutExtensionConverter 获取文件名(无扩展名)
TimeSpanToHourMinuteSecondConverter TimeSpan → HH:mm:ss
TimeSpanToMinuteSecondConverter TimeSpan → mm:ss
NullableToActualConverter 可空类型 → 实际类型值
ObjectToNullableConverter 对象 → 可空值类型

4.16 典型使用示例

<!-- 布尔转可见 -->
<Button Visibility="{Binding IsLoading, Converter={StaticResource TrueToCollapsedConverter}}" />
<!-- 数值比较 -->
<Label Background="{Binding Value, Converter={StaticResource GreaterThanParaNumberConverter}, 
                         ConverterParameter=5}" />
<!-- 键值映射 -->
<Label Content="{Binding Status, Converter={StaticResource BindAsKeyFindValueInParaConverter},
               ConverterParameter='1:待审核 | 2:已通过 | 3:已拒绝'}" />
<!-- 多值逻辑判断(所有条件为真时显示) -->
<Border>
    <Border.Visibility>
        <MultiBinding Converter="{StaticResource AllTrueReturnParaValueMultiConverter}" 
                      ConverterParameter="Visible:Collapsed:1">
            <Binding Path="HasName" />
            <Binding Path="HasAge" />
        </MultiBinding>
    </Border.Visibility>
</Border>

5. 附加属性(Attached Properties)

库提供 15 个附加属性帮助类,位于 Attached/ 目录:

5.1 ButtonAttached(针对 Button)

附加属性 类型 默认值 说明
KeyboardWindowType Type typeof(NumberKeyboard) 自定义键盘窗口类型
IsUseCustomKeyboard bool false 是否使用自定义键盘输入(点击弹出数字键盘)

5.2 LabelAttached(针对 Label)

附加属性 类型 默认值 说明
KeyboardWindowType Type typeof(NumberKeyboard) 自定义键盘窗口类型
IsUseCustomKeyboard bool false 是否使用自定义键盘输入

5.3 RadioButtonAttached(550+ 行,最丰富的附加属性类)

行为类:

附加属性 类型 默认值 说明
IsCanUncheck bool false 是否允许取消选中(再次点击取消勾选)
RadioValue object 选中时的值
RadioBinding object 选中值绑定(BindsTwoWayByDefault

RadioBinding 使用方式:将多个 RadioButton 绑定到同一 ViewModel 属性,每个 RadioButton 设置不同的 RadioValue,替代传统 GroupName 方式。

<RadioButton lib:RadioButtonAttached.RadioBinding="{Binding SelectedOption}" 
             lib:RadioButtonAttached.RadioValue="OptionA" Content="选项A"/>
<RadioButton lib:RadioButtonAttached.RadioBinding="{Binding SelectedOption}" 
             lib:RadioButtonAttached.RadioValue="OptionB" Content="选项B"/>

样式类(20+ 个附加属性,用于自定义 RadioButton 外观):

附加属性 类型 默认值 说明
CornerRadius CornerRadius 0 边框圆角
FixPartMargin Thickness (5,0,0,0) 固定部分(圆圈)边距
FixPartHorizontalAlignment HorizontalAlignment Center 固定部分水平对齐
FixPartVerticalAlignment VerticalAlignment Center 固定部分垂直对齐
ContentPartMargin Thickness (5,0,5,0) 内容部分边距
ContentPartHorizontalAlignment HorizontalAlignment Center 内容部分水平对齐
ContentPartVerticalAlignment VerticalAlignment Center 内容部分垂直对齐
OuterCircleDiameter double 20 外部圆圈直径
InnerCircleDiameter double 14 内部圆圈直径
OuterCircleBorderBrush Brush DimGray 外部圆圈边框颜色
OuterCircleCheckedBorderBrush Brush DodgerBlue 勾选时外部圆圈边框颜色
OuterCircleBorderThickness Thickness 1 外部圆圈边框粗细
OuterCircleFillBrush Brush Transparent 外部圆圈填充颜色
InnerCircleFillBrush Brush DodgerBlue 内部圆圈填充颜色
CheckedForeground Brush DodgerBlue 选中时前景色
CheckedBackground Brush White 选中时背景色
CheckedBorderBrush Brush 选中时边框画刷
CheckedBorderThickness Thickness 1 选中时边框粗细
MouseOverForeground Brush DodgerBlue 鼠标悬停前景色
MouseOverBackground Brush LightBlue 鼠标悬停背景色
MouseOverBorderBrush Brush 鼠标悬停边框画刷
MouseOverBorderThickness Thickness 1 鼠标悬停边框粗细

5.4 ContextMenuAttached

附加属性 类型 默认值 说明
IsLeftClickEnabled bool false 是否允许左键触发右键菜单
<Label lib:ContextMenuAttached.IsLeftClickEnabled="True">
    <Label.ContextMenu>
        <ContextMenu>
            <MenuItem Header="复制" />
            <MenuItem Header="粘贴" />
        </ContextMenu>
    </Label.ContextMenu>
</Label>

5.5 其他附加属性类

类名 说明
DataGridAttached DataGrid 附加属性
ExportPicAttached 导出图片附加功能
FocusAttached 焦点控制附加属性
LocationTargetRenderOriginAttached 元素定位附加属性(TargetElementIsAlignWithCenterIsFlipOrigin
RotateToTranslateAttached / RotateToTranslateAttachedV2 旋转平移附加属性
ScrollViewerAttached ScrollViewer 附加属性
TabControlAttached TabControl 附加属性
TextBoxAttached TextBox 附加属性
WpfTouchAttached 触摸支持附加属性

6. 行为(Behavior)

6.1 SelectedItemsBehavior(命名空间:WPFTemplateLib.Behaviors

继承 Behavior<MultiSelector>,允许对 MultiSelector(如 ListBoxDataGrid)实现可绑定的多选功能。

依赖属性 类型 模式 说明
BindableSelectedItems IList OneWayToSource 绑定选中的项集合
SelectedItemsChangedCommand RelayCommand<IList> 选中项变更时执行的命令
<ListBox SelectionMode="Multiple">
    <b:Interaction.Behaviors>
        <lib:SelectedItemsBehavior BindableSelectedItems="{Binding SelectedUsers}" />
    </b:Interaction.Behaviors>
</ListBox>

6.2 DragInCanvasBehavior

继承 Behavior<UIElement>,实现 Canvas 中拖拽移动功能。通过 MouseLeftButtonDown/Move/Up 事件更新 Canvas.Left  Canvas.Top

6.3 SelectedItemBehavior

继承 Behavior<FrameworkElement>,让包含 RadioButton 的 Panel 或 ItemsControl 拥有可绑定的 SelectedItem 属性。RadioButton 的值存放在 Tag 中。

依赖属性 类型 说明
SelectedItem object 当前选中的项(可通过 Binding 绑定到 ViewModel)
<StackPanel>
    <b:Interaction.Behaviors>
        <lib:SelectedItemBehavior SelectedItem="{Binding SelectedItem}" />
    </b:Interaction.Behaviors>
    <RadioButton Tag="A" Content="选项A" />
    <RadioButton Tag="B" Content="选项B" />
    <RadioButton Tag="C" Content="选项C" />
</StackPanel>

6.4 AttachAdornerBehavior

继承 Behavior<UIElement>,为 UI 元素附加装饰器(BindableContainerAdorner),可在元素上悬浮显示额外内容。

属性/依赖属性 类型 默认值 说明
Element FrameworkElement 装饰内容界面元素
IsShowAdorner bool true 是否显示装饰器
<Image Source="photo.jpg">
    <b:Interaction.Behaviors>
        <lib:AttachAdornerBehavior IsShowAdorner="{Binding ShowOverlay}">
            <lib:AttachAdornerBehavior.Element>
                <Border Background="#AAFFCC00" CornerRadius="8" Height="40">
                    <TextBlock Text="装饰层内容" />
                </Border>
            </lib:AttachAdornerBehavior.Element>
        </lib:AttachAdornerBehavior>
    </b:Interaction.Behaviors>
</Image>

6.5 ChangeAttachedPropertyAction

继承 TriggerAction<DependencyObject>,在事件触发时修改指定类的附加属性值。

属性 类型 说明
ClassType Type 定义附加属性的类类型
PropertyName string 附加属性名称
Value object 设置的值
<b:Interaction.Triggers>
    <b:EventTrigger EventName="MouseDown">
        <lib:ChangeAttachedPropertyAction ClassType="smartAdorner:SmartAdorner" 
                                          PropertyName="Visible" Value="True" />
    </b:EventTrigger>
</b:Interaction.Triggers>

7. 自定义控件(Custom Controls)

7.1 PanelWithMessage

继承 ContentControl,提供主内容区和信息显示区的布局面板。常用于需要底部信息输出的窗口。

依赖属性 类型 默认值 说明
ContentRegionLength GridLength 3* 主内容区域高度比例
MessageRegionLength GridLength 1* 信息区域高度比例
IsEnglish bool false 是否为英文界面
<lib:PanelWithMessage ContentRegionLength="5*">
    <!-- 主内容 -->
    <Grid> ... </Grid>
</lib:PanelWithMessage>

7.2 CircleWithInOutText

继承 Control,内部文字 + 外部文字的圆形控件(带有 17 个依赖属性和 2 个附加属性)。

依赖属性 类型 默认值 说明
CirclePlacement Dock 圆形放置位置
CircleDiameter double 32 圆形直径
CircleStroke Brush 圆形描边色
CircleStrokeThickness double 圆形描边粗细
InnerText string 内部文字
OuterText string 外部文字
InnerTextColor Brush 内部文字颜色
OuterTextColor Brush 外部文字颜色
TextColor Brush 统一文字颜色(通过 PropertyChangedCallback 联动 InnerTextColor/OuterTextColor)
CircleInnerColor Brush 圆形内部颜色
DistanceBetweenCircleAndText double 圆与文字间距
InnerTextFontSize double 内部文字字号
OuterTextFontSize double 外部文字字号
TextFontSize double 统一文字字号
InnerTextFontWeight FontWeight 内部文字粗细
OuterTextFontWeight FontWeight 外部文字粗细
TextFontWeight FontWeight 统一文字粗细
InnerTextBlockStyle Style 内部 TextBlock 样式
OuterTextBlockStyle Style 外部 TextBlock 样式

附加属性: OuterTextHorizontalAlignmentOuterTextVerticalAlignment

注意:CircleWithTextBlock 已被标记为 [Obsolete("使用 CircleWithInOutText 代替")]

7.3 CheckBoxButton

继承 Button,特殊的多选框控件。主要目的是在指定 Command 后不主动改变 IsChecked,而是由 ViewModel 逻辑决定是否勾选。

路由事件 说明
Checked 勾选时触发
Unchecked 取消勾选时触发
IsCheckedChanged IsChecked 变化时触发

主要依赖属性(19个):

依赖属性 类型 默认值 说明
IsChecked bool? 勾选状态(BindsTwoWayByDefault
ContentPosition Dock Right 内容相对勾选框位置
MarkGeometryData string 勾选标志路径数据
MarkFillBrush Brush 勾选标志填充色
MarkStrokeBrush Brush 勾选标志描边色
MarkStrokeThickness double 勾选标志描边粗细
MarkMargin Thickness 勾选标志外边距
MarkRegionMargin Thickness 勾选框外边距
MarkRegionWidth double 勾选框宽度
MarkRegionHeight double 勾选框高度
MarkRegionHorizontalAlignment HorizontalAlignment 勾选框水平对齐
MarkRegionVerticalAlignment VerticalAlignment 勾选框垂直对齐
MarkRegionBorderThickness Thickness 勾选框边框粗细
MarkRegionBorderThicknessWhenChecked Thickness 勾选后边框粗细
MarkRegionBorderCornerRadius CornerRadius 勾选框圆角
MarkRegionBorderBrush Brush 勾选框边框色
MarkRegionBorderBrushWhenChecked Brush 勾选后边框色
MarkRegionBackgroundWhenChecked Brush 勾选后背景色
ForegroundWhenChecked Brush 勾选后前景色
IsLikeRadioButton bool 是否模仿 RadioButton 样式
ContentRegionMargin Thickness 内容区域边距
<lib:CheckBoxButton Content="指定了 Command" 
                    IsChecked="{Binding IsCbbChecked}"
                    Command="{Binding ClickCheckBoxButtonCmd}" />

7.4 AutoGrid

继承 Grid,自动排列子元素的网格控件(源于 WpfAutoGrid 项目)。

依赖属性 类型 默认值 说明
ChildHorizontalAlignment HorizontalAlignment? 子元素水平对齐
ChildMargin Thickness? 子元素边距
ChildVerticalAlignment VerticalAlignment? 子元素垂直对齐
ColumnCount int 列数
Columns string 列定义(逗号分隔的 GridLength,如 *,2*,Auto
ColumnWidth GridLength 默认列宽
IsAutoIndexing bool 是否自动索引
Orientation Orientation 排列方向
RowCount int 行数
Rows string 行定义
RowHeight GridLength 默认行高
<lib:AutoGrid ColumnCount="3" ColumnWidth="*" RowCount="2" RowHeight="*" ChildMargin="2">
    <Rectangle Fill="Blue" Grid.ColumnSpan="2" />
    <Rectangle Fill="Red" />
    <Rectangle Fill="Yellow" />
    <Rectangle Fill="Green" Grid.ColumnSpan="2" />
</lib:AutoGrid>

7.5 TitleValueUnit

继承 Control,展示”标题-值-单位”的控件。

依赖属性 类型 默认值 说明
Title string 标题文字
Value object 值内容
Unit string 单位文字
SetValueCommand ICommand 设置值命令
TitlePosition Dock Top 标题位置
TitleMargin Thickness 标题边距
TitleWidth double NaN 标题宽度
TitleTextAlignment TextAlignment Left 标题文字对齐
ValueRegionMargin Thickness 值区域边距
ContentStringFormat string 内容格式化字符串
TitleFontSize double 标题字号
ValueFontSize double 值字号
UnitFontSize double 单位字号

附加属性: TitleForegroundContentForegroundUnitForegroundTitleFontWeightContentFontWeightUnitFontWeight

7.6 ManualComboBox

继承 ComboBox,下拉选择后只触发 SelectedItemChangedCommand 而不主动改变 SelectedItem。内部通过备份选中项、截获点击事件来恢复原选中项(通过 RestoreBindingValue 方法处理绑定恢复)。

7.7 TitleContentUnit

继承 ContentControl,简化的标题-内容-单位控件。

依赖属性 类型 说明
Title string 标题
Unit string 单位

7.8 CornerClip / CenterRectClip

  • CornerClip:圆角裁剪控件,将子内容裁剪为指定 CornerRadius
  • CenterRectClip:中央矩形裁剪,通过 HorizontalKeepPercent 控制保留比例
<lib:CornerClip CornerRadius="{Binding CornerRadius, RelativeSource={RelativeSource AncestorType=Border}}">
    <Grid Background="Chartreuse">...</Grid>
</lib:CornerClip>

7.9 DateTimePicker

继承控件,日期时间选择器。支持中英文样式切换:

  • 默认样式:中文日期选择器
  • LibSty.DateTimePicker.English:英文版样式
依赖属性 类型 说明
SelectedDateTime DateTime? 选中的日期时间
<lib:DateTimePicker SelectedDateTime="{Binding MyDateTime}" Height="32" Width="300" />
<lib:DateTimePicker Style="{StaticResource LibSty.DateTimePicker.English}" 
                    SelectedDateTime="{Binding MyDateTime}" />

7.10 FlipableControl / FlipableContentControl

可翻转面板控件,支持水平/垂直翻转动画。

属性 类型 说明
IsFlip bool 是否翻转
FlipType 翻转类型(Horizontal / Vertical)

7.11 UniformSpacingPanel

自动均匀分布子元素的布局面板。

依赖属性 类型 说明
Orientation Orientation 排列方向
Spacing double 元素间距
ChildWrapping 子元素换行模式
ItemWidth / ItemHeight double 子元素统一宽/高
ItemVerticalAlignment VerticalAlignment 子元素垂直对齐

7.12 MetroHeader

继承 MahApps MetroHeader,带标题的分组容器。

7.13 Toast(气泡弹窗)

完整的自定义气泡弹窗实现(638 行代码,位于 Controls/WpfToast/)。

ToastOptions 类(17 个属性):

属性 说明
Icon 图标类型(ToastIcons 枚举)
Location 显示位置(ToastLocation 枚举,17 个位置)
Time 显示持续时间(毫秒)
TextWidth 文字宽度
ToastWidth / ToastMaxWidth 弹窗宽度
IconForeground 图标前景色

ToastIcons 枚举: NoneInformationErrorWarningBusy

ToastLocation 枚举(17 个位置): ScreenCenterOwnerCenterScreenTopLeftScreenTopRightScreenBottomLeftScreenBottomRightOwnerTopLeft 等。

静态使用方法:

// 屏幕中间弹窗
Toast.Show("操作成功", new ToastOptions { 
    Icon = ToastIcons.Information, 
    Location = ToastLocation.ScreenCenter, 
    Time = 3000 
});

// 窗口中间弹窗
Toast.Show(win, "请先选择一项", new ToastOptions {
    Icon = ToastIcons.Warning,
    Location = ToastLocation.OwnerCenter,
    Time = 5000,
});

ToastHelper 静态帮助类:

方法 说明
ToastToScreen(msg, icon, ms) 屏幕中间弹窗
ToastToScreenWarning(msg, ms) 屏幕中间警告弹窗
ToastToScreenError(msg, ms) 屏幕中间错误弹窗
ToastToWindow(win, msg, ms) 窗口中间弹窗
ToastToWindowError(win, msg, ms) 窗口中间错误弹窗

7.14 PasswordInput

密码输入控件(FruitVent 设计风格),支持明文切换和清除按钮。

依赖属性 类型 说明
AllowClear bool 是否显示清除按钮
IsShowOriginText bool 是否显示明文
<lib:PasswordInput AllowClear="True" IsShowOriginText="{Binding ShowPassword}" />

7.15 Row / Col(HandyGrid)

HandyControl 风格的栅格布局控件,位于 Controls/Panels/HandyGrid/

  • Row:栅格行容器
  • Col:栅格列,Span 属性控制占位宽度

7.16 SeparatorStackPanel / RenderedSeparatorStackPanel / AdornerSeparatorStackPanel

三种带分隔线的 StackPanel:

  • SeparatorStackPanel:通过 Separator 控件实现分隔
  • RenderedSeparatorStackPanel(推荐):通过渲染方式绘制分隔线,SeparatorBrush/SeparatorInset/SeparatorThickness 属性控制外观
  • AdornerSeparatorStackPanel:通过 Adorner 层绘制分隔线

7.17 Form / FormItem(XUI)

位于 Controls/XUI/,加载时带动画效果的 ItemsControl 列表。

  • Form:继承 ItemsControl,Columns/Rows 属性控制网格布局
  • FormItem:带图标、标题、内容区的列表项,支持 IconTitleHeaderWidth 等属性
<xui:Form ItemsSource="{Binding Datas}" Columns="2" Rows="2">
    <xui:Form.ItemTemplate>
        <DataTemplate>
            <xui:FormItem Title="字段名" Icon="icon.png">
                <TextBox Text="{Binding Value}" />
            </xui:FormItem>
        </DataTemplate>
    </xui:Form.ItemTemplate>
</xui:Form>

8. 标记扩展(Markup Extensions)

位于 MarkupExtensions/ValueMarkupExtensions.cs,提供 14 种基本数据类型的标记扩展。

标记扩展 类型 说明
ByteValue byte 提供 byte 值
ShortValue short 提供 short 值
IntValue int 提供 int 值
LongValue long 提供 long 值
FloatValue float 提供 float 值
DoubleValue double 提供 double 值
DecimalValue decimal 提供 decimal 值
CharValue char 提供 char 值
BoolValue bool 提供 bool 值
VisibilityValue Visibility 提供 Visibility 枚举值
MediaColorValue Color 颜色字符串(RGB/ARGB)→System.Windows.Media.Color
NullableMediaColorValue Color? 颜色字符串 → 可空 Color?
SolidColorBrushValue SolidColorBrush 颜色字符串 →SolidColorBrush
<!-- 在属性中使用标记扩展 -->
<Label Background="{lib:SolidColorBrushValue ColorStr='#AABBCC'}" />
<TextBlock Visibility="{lib:VisibilityValue Value={x:Static Visibility.Visible}}" />

9. 帮助类(Helpers)

库提供丰富的帮助类,按功能分组:

9.1 WpfHelpers 目录

类名 说明
BitmapHelper Bitmap 帮助类
ExportPicHelper 导出图片帮助类
FrameworkElementHelper FrameworkElement 扩展帮助
MathHelper 数学运算帮助
MediaColorHelper 媒体颜色帮助(字符串与 Color/SolidColorBrush 互转)
MouseHelper 鼠标操作帮助
RenderHelper 渲染帮助
ScreenHelper 屏幕信息帮助
ScrollHelper 滚动帮助
UiHelper UI 通用帮助
WpfRealTimeTouchHelper 实时触摸帮助
WpfWindowHelper 窗口操作帮助

9.2 Attached 目录

类名 说明
AttachAdornerHelper 附加装饰器帮助类(可替代 Behavior 方式)
ClickAndTouchHelper / ClickAndTouchHelperV2 点击和触摸帮助
GridHelper Grid 附加帮助
MultiSelectorHelper 多选控件帮助
PasswordBoxHelper PasswordBox 附加帮助
WpfTouchScrollHelper 触摸滚动帮助

9.3 其他工具类

类名 位置 说明
CustomKeyboardHelper CustomKeyboard/ 自定义键盘帮助
TextBoxStyleHelper Styles/ 文本框样式帮助
TokenizerHelper Utilities/ 分词器帮助
ValidateHelper Utilities/ 验证帮助
CompareHelper WpfConverters/Core/ 比较帮助
ConverterHelper WpfConverters/Core/ 转换器帮助

10. 配置属性系统(ConfigManager)

位于 ConfigUtil/ 目录(命名空间:WPFTemplate),提供 JSON 文件配置持久化能力。

类型 说明
IConfigItems 空标记接口,配置类需实现此接口
ConfigManager 静态帮助类,提供 SaveConfig  LoadConfig<T> 方法
ConfigItems 默认配置类实现

使用方法:

// 1. 定义配置类
public class AppConfig : IConfigItems
{
    public string LastFilePath { get; set; }
    public int WindowWidth { get; set; } = 800;
    public int WindowHeight { get; set; } = 600;
}

// 2. 保存配置
var config = new AppConfig { LastFilePath = @"D:\data.txt" };
ConfigManager.SaveConfig(config);

// 3. 加载配置
var (isSucceed, config) = ConfigManager.LoadConfig<AppConfig>();
if (isSucceed)
{
    // 使用 config.WindowWidth、config.WindowHeight...
}

配置文件自动保存在应用程序根目录下 ConfigItems.json(文件名取自 ConfigItems 类名),保存时自动创建 .bak 备份。


11. 增强集合类

11.1 FixedCountObservableCollection

固定容量的 ObservableCollection<T>。当元素数量超过指定容量时,自动移除最旧(或最新)的元素。

构造参数 类型 默认值 说明
count int 100 最大容量
removeOldest bool true 超容量时移除最旧元素(false 则移除最新)
// 保留最近 200 条日志
var logs = new FixedCountObservableCollection<string>(200, removeOldest: true);

11.2 RangeObservableCollection

支持批量操作的 ObservableCollection<T>,添加/移除大量元素时避免逐个触发 CollectionChanged

方法 说明
BatchUpdate() 开始批量更新(暂停通知)
EndBatchUpdate() 结束批量更新(恢复通知)
AddRange(IEnumerable<T>) 批量添加(发送 Reset 通知)
RemoveRange(IEnumerable<T>) 批量移除(发送 Reset 通知)
ClearBatch() 批量清空(发送 Reset 通知)
var list = new RangeObservableCollection<string>();
list.BatchUpdate();
list.AddRange(new[] { "A", "B", "C", "D", "E" });
list.EndBatchUpdate();

12. 装饰器(Adorner)

BindableContainerAdorner

可绑定的容器装饰器,配合 AttachAdornerBehavior 使用。

SmartAdorner(命名空间:WPFTemplateLib.Adorners.SmartAdorner

智能装饰器系统,提供可拖拽、可调整大小的装饰器层:

  • SmartAdorner.Visible(附加属性):控制装饰器是否显示
  • SmartAdorner.Template(附加属性):装饰器内容模板
  • DragThumb:可拖拽的拖拽点控件(X/Y 绑定坐标)
  • ResizingAdorner:可调整大小的装饰器(Width/Height/MinWidth/MaxWidth/MinHeight/MaxHeight

XamlAdorner(命名空间:WPFTemplateLib.Adorners.XamlAdorner

  • AdornedControl:带装饰器的控件容器,支持 AdornerContentIsAdornerVisibleHorizontalAdornerPlacementVerticalAdornerPlacementAdornerOffsetX 等属性

使用示例(来自 WPFPractice 项目)

以下示例摘自 WPFPractice 示例项目中的实际代码。

示例 1:PanelWithMessage + TabControl 整合

<lib:PanelWithMessage ContentRegionLength="5*">
    <TabControl>
        <TabItem Header="X.UI:Form">
            <xui:Form ItemsSource="{Binding Datas}">
                <xui:Form.ItemTemplate>
                    <DataTemplate>
                        <xui:FormItem Title="字段">
                            <TextBox Text="{Binding Value}" />
                        </xui:FormItem>
                    </DataTemplate>
                </xui:Form.ItemTemplate>
            </xui:Form>
        </TabItem>
    </TabControl>
</lib:PanelWithMessage>

示例 2:CheckBoxButton 多样化样式

<!-- 默认样式 -->
<lib:CheckBoxButton Content="默认样式" IsChecked="{Binding IsCbbChecked}" />
<!-- Command 不主动改变 IsChecked -->
<lib:CheckBoxButton Content="指定了 Command" 
                    IsChecked="{Binding IsCbbChecked}"
                    Command="{Binding ClickCheckBoxButtonCmd}" />
<!-- 自定义外观 -->
<lib:CheckBoxButton Content="更改勾选框大小" 
                    MarkRegionWidth="20" MarkRegionHeight="20" MarkStrokeThickness="3" />
<lib:CheckBoxButton Content="勾选后边框变色" 
                    MarkRegionBorderBrushWhenChecked="Gold" MarkRegionBorderThicknessWhenChecked="3" />
<lib:CheckBoxButton Content="文字放在顶部" ContentPosition="Top" />
<!-- 模仿 RadioButton -->
<lib:CheckBoxButton Content="模仿 RadioButton" 
                    Style="{StaticResource LibSty.CheckBoxButton.LikeRadioButton}" />

示例 3:SmartAdorner 拖拽系统

<ListBox ItemsSource="{Binding Elements}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Canvas.Left" Value="{Binding X}" />
            <Setter Property="Canvas.Top" Value="{Binding Y}" />
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Background="AntiqueWhite" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Rectangle smartAdorner:SmartAdorner.Visible="{Binding IsSelected}" 
                       Width="{Binding Width}" Height="{Binding Height}" 
                       Stroke="Blue" Fill="White">
                <smartAdorner:SmartAdorner.Template>
                    <DataTemplate>
                        <smartAdorner:ResizingAdorner Width="{Binding Width}" Height="{Binding Height}"
                            MinWidth="10" MinHeight="20" MaxWidth="200" MaxHeight="400"
                            X="{Binding X}" Y="{Binding Y}" />
                    </DataTemplate>
                </smartAdorner:SmartAdorner.Template>
            </Rectangle>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

示例 4:RadioButton 绑定值

<StackPanel>
    <RadioButton Content="选项A" lib:RadioButtonAttached.RadioBinding="{Binding SelectedOption}" 
                 lib:RadioButtonAttached.RadioValue="A" />
    <RadioButton Content="选项B" lib:RadioButtonAttached.RadioBinding="{Binding SelectedOption}" 
                 lib:RadioButtonAttached.RadioValue="B" />
    <RadioButton Content="选项C" lib:RadioButtonAttached.RadioBinding="{Binding SelectedOption}" 
                 lib:RadioButtonAttached.RadioValue="C" />
</StackPanel>

示例 5:转换器组合使用(BoolResultConverterToOtherResultConverter)

<!-- 输入框为空时背景色变化 -->
<Label Content="输入框为空时此处背景色变化"
       Background="{Binding InputText, 
           Converter={lib:BoolResultConverterToOtherResultConverter 
               ValueConverter={StaticResource IsNullOrWhitespaceConverter},
               ResultGetMode=Direct, 
               TrueResult={lib:SolidColorBrushValue ColorStr='#AABBCC'}, 
               FalseResult={lib:SolidColorBrushValue ColorStr='#FFCCBB'}}}" />

版本历史

版本号 更新日期 重要更新
7.3.1.0 2025-10 当前版本,完善自定义控件和转换器
7.3.0.0 2025-06 Toast 控件重构,增加 ViewModelBase 基类
7.2.0.0 2025-03 增加 PasswordInput、SeparatorStackPanel 系列控件
7.1.0.0 2024-12 增加 FruitVent 设计风格控件,主题系统优化
7.0.0.0 2024-09 重构为 net6.0-windows + net472 双目标框架
6.30.0.0 2024-06 增加 SmartAdorner 智能装饰器系统
6.29.0.0 2024-03 CheckBoxButton 重构,增加多项外观定制属性
6.28.0.0 2023-12 AutoGrid 控件引入,WpfAutoGrid 项目合并
6.27.0.0 2023-09 转换器大幅扩充,增加比较转换器系列
6.26.02.0101 2023-06 FlipableControl 控件引入
6.24.0.0 2022-12 引入 PropertyChanged.Fody 支持,SimpleBindableBase
6.21.0.0 2022-05 ViewModelBase 加入 Toast 命令支持

相关资源


声明

WPFTemplateLib 由 独立观察员(DLGCY) 开发和维护,供免费使用。本库中包含的部分第三方代码(如 AutoGrid、SelectedItemBehavior 等)已在源码中标注原始出处及许可信息。使用本库时,请尊重各模块的原始许可条款。

原创文章,转载请注明: 转载自 独立观察员(dlgcy.com)

本文链接地址: [WPFTemplateLib — WPF 帮助类库](https://dlgcy.com/wpftemplatelib/)

关注微信公众号 独立观察员博客(DLGCY_BLOG) 第一时间获取最新文章

%title插图%num

发表评论