Compare commits

...
10 Commits
Author SHA1 Message Date
chfei 72d9b295a0 Release HandyControl 3.6.1.0 with default Chinese resources
Build / build (push) Canceled after 0s
2026-10-26 18:57:38 +08:00
NaBian e9ad3d701b Update README-cn 2026-10-15 11:26:57 +08:00
NaBian f59db915f7 Update README 2026-10-15 10:56:41 +08:00
NaBian 2c0875ebd6 feat: Add Dialog styles and demo. 2026-06-27 17:36:21 +08:00
NaBian cb7e6fbb98 feat: Add ImageSelector styles and demo. 2026-06-20 22:30:38 +08:00
NaBian 7da3acceb1 feat: Add Pagination control, style and demo. 2026-06-20 20:15:14 +08:00
NaBian 2c91527181 feat: Add GotoTop control, style and demo. 2026-06-20 19:40:46 +08:00
NaBian 550b980f54 feat: Add SearchBar control, themes and demo. 2026-06-20 18:16:14 +08:00
NaBian aa32f72563 feat: Add PinBox control, styles and demo. 2026-06-20 17:55:51 +08:00
NaBian c48a634220 feat: Add ProgressButton control and demo. 2026-06-20 16:35:26 +08:00
50 changed files with 3610 additions and 59 deletions

No files matched your search

+2
View File
@@ -8,3 +8,5 @@ packages/
build/outputs
build/tools
.DS_Store
*.nupkg
*.snupkg
+3
View File
@@ -1,3 +1,6 @@
<img width="1920" height="2930" alt="image" src="https://github.com/user-attachments/assets/ffcc0977-f408-465c-bb7a-6ece78b39991" />
## 友情链接
[SimpleFactoryGenerator](https://github.com/DingpingZhang/SimpleFactoryGenerator) - A simple factory source generator that enables the pattern to not violate the open-close principle.
+3
View File
@@ -1,3 +1,6 @@
<img width="1920" height="2930" alt="image" src="https://github.com/user-attachments/assets/ffcc0977-f408-465c-bb7a-6ece78b39991" />
## Blogroll
[SimpleFactoryGenerator](https://github.com/DingpingZhang/SimpleFactoryGenerator) - A simple factory source generator that enables the pattern to not violate the open-close principle.
@@ -42,9 +42,14 @@
"group": true,
"demoItemList": [
[ "ConfettiCannon", "ConfettiCannonDemo", "Brush.Favorite", "", "Interacting" ],
[ "Dialog", "DialogDemo", "Brush.Dialog", "", "Feedback" ],
[ "Gravatar", "GravatarDemo", "Brush.User", "", "DataDisplay" ],
[ "ButtonGroup", "ButtonGroupDemo", "Brush.ButtonGroup", "", "Button" ],
[ "ProgressButton", "ProgressButtonDemo", "Brush.ProgressBarStatusBar8", "", "Button" ],
[ "Card", "CardDemo", "Brush.ContactCard", "", "DataDisplay" ],
[ "GotoTop", "GotoTopDemo", "Brush.GoToTop", "", "Interacting" ],
[ "PinBox", "PinBoxDemo", "Brush.Ellipsis", "", "DataEntry" ],
[ "SearchBar", "SearchBarDemo", "Brush.Search", "", "DataEntry" ],
[ "ElementGroup", "ElementGroupDemo", "Brush.ButtonGroup", "", "Layout" ],
[ "CirclePanel", "CirclePanelDemo", "Brush.ColorWheel", "", "Layout" ],
[ "Grid", "GridDemo", "Brush.GridPane", "", "Layout" ],
@@ -54,12 +59,14 @@
[ "UniformSpacingPanel", "UniformSpacingPanelDemo", "Brush.IncreaseHorizontalSpacing", "", "Layout" ],
[ "ProgressBar", "ProgressBarDemo", "Brush.ProgressBar", "", "Feedback" ],
[ "Rate", "RateDemo", "Brush.Favorite", "", "Feedback" ],
[ "Pagination", "PaginationDemo", "Brush.Paginator", "", "Navigation" ],
[ "Loading", "LoadingDemo", "Brush.Loading", "", "Feedback" ],
[ "Tag", "TagDemo", "Brush.Tag", "", "DataDisplay" ],
[ "Badge", "BadgeDemo", "Brush.CheckDot", "", "DataDisplay" ],
[ "Shield", "ShieldDemo", "Brush.SplitKeyValuePair", "", "DataDisplay" ],
[ "ImageBlock", "ImageBlockDemo", "Brush.ImageStack", "", "DataDisplay" ],
[ "AnimationPath", "AnimationPathDemo", "Brush.Path", "", "DataDisplay" ]
[ "AnimationPath", "AnimationPathDemo", "Brush.Path", "", "DataDisplay" ],
[ "ImageSelector", "ImageSelectorDemo", "Brush.Image", "", "DataEntry" ]
]
}
]
@@ -1,13 +1,20 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using HandyControl.Controls;
using HandyControlDemo.Data;
using HandyControlDemo.UserControl;
using HandyControlDemo.ViewModel;
namespace HandyControlDemo;
public partial class MainWindow : Window
public partial class MainWindow : Avalonia.Controls.Window
{
public MainWindow() => InitializeComponent();
public MainWindow()
{
InitializeComponent();
Dialog.SetToken(this, MessageToken.MainWindow);
}
protected override void OnLoaded(RoutedEventArgs e)
{
@@ -0,0 +1,22 @@
<Border x:Class="HandyControlDemo.UserControl.InteractiveDialog"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
CornerRadius="10"
Width="400"
Height="247"
Background="{DynamicResource RegionBrush}">
<StackPanel VerticalAlignment="Center"
Margin="32"
Spacing="32">
<TextBlock Theme="{StaticResource TextBlockLargeBold}"
Text="{Binding Message}" />
<TextBox Text="{Binding Result, Mode=TwoWay}"
Theme="{StaticResource TextBoxExtend}" />
<Button Width="120"
Command="{Binding CloseCommand}"
Theme="{StaticResource ButtonPrimary}"
HorizontalAlignment="Center"
Content="OK" />
</StackPanel>
</Border>
@@ -0,0 +1,14 @@
using Avalonia.Controls;
using HandyControlDemo.ViewModel;
namespace HandyControlDemo.UserControl;
public partial class InteractiveDialog : Border
{
public InteractiveDialog()
{
InitializeComponent();
DataContext = new InteractiveDialogViewModel();
}
}
@@ -0,0 +1,25 @@
<Border x:Class="HandyControlDemo.UserControl.TextDialog"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
CornerRadius="10"
Width="400"
Height="247"
Background="{DynamicResource RegionBrush}">
<Panel>
<TextBlock Theme="{StaticResource TextBlockLargeBold}"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="Please wait..." />
<Button x:Name="CloseButton"
Width="22"
Height="22"
Theme="{StaticResource ButtonIcon}"
Foreground="{DynamicResource PrimaryBrush}"
hc:IconElement.Geometry="{StaticResource ErrorGeometry}"
Padding="0"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Margin="0,4,4,0" />
</Panel>
</Border>
@@ -0,0 +1,15 @@
using Avalonia.Controls;
using Avalonia.VisualTree;
using HandyControl.Controls;
namespace HandyControlDemo.UserControl;
public partial class TextDialog : Border
{
public TextDialog()
{
InitializeComponent();
CloseButton.Click += (_, _) => this.FindAncestorOfType<Dialog>()?.Close();
}
}
@@ -0,0 +1,35 @@
<Border x:Class="HandyControlDemo.UserControl.TextDialogWithTimer"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
CornerRadius="10"
Width="400"
Height="247"
Background="{DynamicResource RegionBrush}">
<Panel>
<Viewbox Width="80"
Height="80"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<TextBlock TextWrapping="Wrap"
Theme="{StaticResource TextBlockLargeBold}"
Text="Please wait..." />
</Viewbox>
<Button x:Name="CloseButton"
Width="22"
Height="22"
Foreground="{DynamicResource PrimaryBrush}"
hc:IconElement.Geometry="{StaticResource ErrorGeometry}"
Padding="0"
Theme="{StaticResource ButtonIcon}"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Margin="0,4,4,0" />
<hc:CircleProgressBar x:Name="ProgressBarTimer"
ShowText="False"
Width="120"
Height="120"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Panel>
</Border>
@@ -0,0 +1,44 @@
using System;
using Avalonia.Controls;
using Avalonia.Threading;
using Avalonia.VisualTree;
using HandyControl.Controls;
using HandyControlDemo.ViewModel;
namespace HandyControlDemo.UserControl;
public partial class TextDialogWithTimer : Border
{
public TextDialogWithTimer()
{
InitializeComponent();
DataContext = new InteractiveDialogViewModel();
var startTime = DateTime.Now;
var timer = new DispatcherTimer(DispatcherPriority.ApplicationIdle)
{
Interval = TimeSpan.FromMilliseconds(50)
};
timer.Tick += (_, _) =>
{
var elapsed = (DateTime.Now - startTime).TotalMilliseconds;
var progress = Math.Min(elapsed / 5000.0 * 100, 100);
ProgressBarTimer.Value = progress;
if (progress >= 100)
{
timer.Stop();
this.FindAncestorOfType<Dialog>()?.Close();
}
};
timer.Start();
CloseButton.Click += (_, _) =>
{
timer.Stop();
this.FindAncestorOfType<Dialog>()?.Close();
};
}
}
@@ -0,0 +1,46 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:vm="clr-namespace:HandyControlDemo.ViewModel"
xmlns:sys="clr-namespace:System;assembly=System.Runtime"
x:Class="HandyControlDemo.UserControl.DialogDemo"
DataContext="{Binding DialogDemo, Source={x:Static vm:ViewModelLocator.Instance}}"
Background="{DynamicResource RegionBrush}"
MinWidth="500">
<hc:DialogContainer>
<TransitioningContentControl>
<Panel>
<StackPanel Margin="32"
VerticalAlignment="Center">
<Button Content="TextDialog"
Command="{Binding ShowTextCommand}" />
<Button Margin="0,32,0,0"
Content="TextDialog(In control)"
Command="{Binding ShowTextCommand}"
CommandParameter="{Binding $parent[UserControl]}" />
<Button Margin="0,32,0,0"
Content="TextDialog with timer"
Command="{Binding ShowInteractiveDialogCommand}">
<Button.CommandParameter>
<sys:Boolean>True</sys:Boolean>
</Button.CommandParameter>
</Button>
<TextBox Margin="0,32,0,0"
Text="{Binding DialogResult}"
Theme="{StaticResource TextBoxExtend}"
Watermark="Please input..." />
<Button Margin="0,10,0,0"
Content="InteractiveDialog"
Command="{Binding ShowInteractiveDialogCommand}">
<Button.CommandParameter>
<sys:Boolean>False</sys:Boolean>
</Button.CommandParameter>
</Button>
<Button Margin="0,32,0,0"
Content="New window"
Command="{Binding NewWindowCommand}" />
</StackPanel>
</Panel>
</TransitioningContentControl>
</hc:DialogContainer>
</UserControl>
@@ -0,0 +1,16 @@
using HandyControl.Controls;
using HandyControlDemo.Data;
using HandyControlDemo.ViewModel;
namespace HandyControlDemo.UserControl;
public partial class DialogDemo : Avalonia.Controls.UserControl
{
public DialogDemo()
{
InitializeComponent();
DataContext = ViewModelLocator.Instance.DialogDemo;
Dialog.SetToken(this, MessageToken.DialogContainer);
}
}
@@ -0,0 +1,34 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
x:Class="HandyControlDemo.UserControl.GotoTopDemo"
Background="{DynamicResource RegionBrush}">
<TransitioningContentControl>
<Panel Height="400">
<ScrollViewer x:Name="ScrollViewerDemo"
Height="390"
VerticalAlignment="Top"
Margin="0,10,0,0">
<Border Height="2000"
Margin="8,0">
<Border.Background>
<LinearGradientBrush StartPoint="50%,0%"
EndPoint="50%,100%">
<GradientStop Offset="0"
Color="White" />
<GradientStop Offset="1"
Color="Black" />
</LinearGradientBrush>
</Border.Background>
</Border>
</ScrollViewer>
<hc:GotoTop Animated="True"
AutoHiding="True"
AnimationTime="500"
Target="{Binding #ScrollViewerDemo}"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Margin="0,0,20,20" />
</Panel>
</TransitioningContentControl>
</UserControl>
@@ -0,0 +1,9 @@
namespace HandyControlDemo.UserControl;
public partial class GotoTopDemo : Avalonia.Controls.UserControl
{
public GotoTopDemo()
{
InitializeComponent();
}
}
@@ -0,0 +1,32 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
x:Class="HandyControlDemo.UserControl.ImageSelectorDemo"
Background="{DynamicResource RegionBrush}">
<ScrollViewer>
<hc:UniformSpacingPanel Margin="32"
ChildWrapping="Wrap"
VerticalAlignment="Center"
Spacing="32"
HorizontalAlignment="Center">
<hc:ImageSelector Width="100" Height="100" />
<hc:ImageSelector Width="100" Height="100"
hc:BorderElement.CornerRadius="50" />
<hc:ImageSelector Width="100" Height="100"
hc:BorderElement.CornerRadius="50"
StrokeDashArray="10,5" />
<hc:ImageSelector Width="100" Height="100"
hc:BorderElement.CornerRadius="50"
BorderBrush="{DynamicResource SuccessBrush}" />
<hc:ImageSelector Width="100" Height="100"
hc:BorderElement.CornerRadius="50"
StrokeDashArray="10,5,10"
BorderBrush="{DynamicResource DangerBrush}" />
<hc:ImageSelector Width="100" Height="100"
hc:BorderElement.CornerRadius="10"
StrokeThickness="2"
BorderThickness="2"
BorderBrush="{DynamicResource PrimaryBrush}" />
</hc:UniformSpacingPanel>
</ScrollViewer>
</UserControl>
@@ -0,0 +1,9 @@
namespace HandyControlDemo.UserControl;
public partial class ImageSelectorDemo : Avalonia.Controls.UserControl
{
public ImageSelectorDemo()
{
InitializeComponent();
}
}
@@ -0,0 +1,51 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="HandyControlDemo.UserControl.PaginationDemo"
Background="{DynamicResource RegionBrush}">
<TransitioningContentControl>
<Grid Margin="32"
RowDefinitions="Auto,*">
<hc:Pagination x:Name="PaginationCtl"
MaxPageCount="10"
DataCountPerPage="10"
PageIndex="1"
IsJumpEnabled="True"
PageUpdated="Pagination_OnPageUpdated" />
<Border Grid.Row="1"
MaxWidth="600"
Margin="0,16,0,0"
Padding="12"
BorderBrush="{DynamicResource BorderBrush}"
Background="{DynamicResource RegionBrush}">
<Grid RowDefinitions="Auto,*">
<TextBlock Text="Current Page Data"
FontWeight="Bold"
Margin="0,0,0,8" />
<ListBox Grid.Row="1"
ItemsSource="{Binding DataList}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="60,160,90,*"
Margin="0,4">
<TextBlock Grid.Column="0"
Text="{Binding Index}" />
<TextBlock Grid.Column="1"
Text="{Binding Name}" />
<TextBlock Grid.Column="2"
Text="{Binding Type}" />
<TextBlock Grid.Column="3"
Text="{Binding Remark}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
</Grid>
</TransitioningContentControl>
</UserControl>
@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using HandyControl.Data;
using HandyControlDemo.Data;
namespace HandyControlDemo.UserControl;
public partial class PaginationDemo : Avalonia.Controls.UserControl
{
private readonly List<DemoDataModel> _totalDataList;
public static readonly DirectProperty<PaginationDemo, ObservableCollection<DemoDataModel>> DataListProperty =
AvaloniaProperty.RegisterDirect<PaginationDemo, ObservableCollection<DemoDataModel>>(nameof(DataList), o => o.DataList);
public PaginationDemo()
{
InitializeComponent();
DataContext = this;
_totalDataList = BuildDataList(100);
DataList = new ObservableCollection<DemoDataModel>();
LoadPage(1, 10);
}
public ObservableCollection<DemoDataModel> DataList { get; }
private void Pagination_OnPageUpdated(object? sender, FunctionEventArgs<int> e)
{
var page = Math.Max(e.Info, 1);
LoadPage(page, 10);
}
private void LoadPage(int page, int pageSize)
{
DataList.Clear();
foreach (var item in _totalDataList.Skip((page - 1) * pageSize).Take(pageSize))
{
DataList.Add(item);
}
}
private static List<DemoDataModel> BuildDataList(int total)
{
var list = new List<DemoDataModel>();
for (var i = 1; i <= total; i++)
{
list.Add(new DemoDataModel
{
Index = i,
Name = $"Name{i}",
IsSelected = i % 2 == 0,
Type = (DemoType)(i % 6 + 1),
ImgPath = string.Empty,
Remark = new string((i % 10).ToString()[0], 10)
});
}
return list;
}
}
@@ -0,0 +1,26 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
x:Class="HandyControlDemo.UserControl.PinBoxDemo"
Background="{DynamicResource RegionBrush}">
<TransitioningContentControl>
<hc:UniformSpacingPanel Spacing="16"
Orientation="Vertical"
Margin="32"
VerticalAlignment="Center">
<hc:PinBox Length="4"
Password="1234"
Completed="PinBox_OnCompleted" />
<hc:PinBox x:Name="PinBoxUnsafe"
Length="4"
Password="1234"
IsSafeEnabled="False"
Completed="PinBox_OnCompleted" />
<TextBox Text="{Binding #PinBoxUnsafe.UnsafePassword, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<hc:PinBox Length="6"
Password="123456"
PasswordChar="❤"
Completed="PinBox_OnCompleted" />
</hc:UniformSpacingPanel>
</TransitioningContentControl>
</UserControl>
@@ -0,0 +1,29 @@
using Avalonia.Interactivity;
using HandyControl.Controls;
using System;
using System.Reflection;
namespace HandyControlDemo.UserControl;
public partial class PinBoxDemo : Avalonia.Controls.UserControl
{
public PinBoxDemo()
{
InitializeComponent();
}
private void PinBox_OnCompleted(object? sender, RoutedEventArgs e)
{
if (e.Source is PinBox pinBox)
{
TryShowGrowl(pinBox.Password);
}
}
private static void TryShowGrowl(string message)
{
var growlType = Type.GetType("HandyControl.Controls.Growl, HandyControl");
var infoMethod = growlType?.GetMethod("Info", BindingFlags.Public | BindingFlags.Static, [typeof(string), typeof(string)]);
infoMethod?.Invoke(null, [message, string.Empty]);
}
}
@@ -0,0 +1,81 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
x:Class="HandyControlDemo.UserControl.ProgressButtonDemo">
<ScrollViewer>
<WrapPanel Margin="16"
VerticalAlignment="Center">
<StackPanel Margin="16"
Spacing="0">
<hc:ProgressButton Width="180"
Margin="5"
Progress="{Binding Progress}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
<hc:ProgressButton Width="180"
Margin="5"
Theme="{StaticResource ProgressButtonPrimary}"
Progress="{Binding Progress}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
<hc:ProgressButton Width="180"
Margin="5"
Theme="{StaticResource ProgressButtonSuccess}"
Progress="{Binding Progress}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
<hc:ProgressButton Width="180"
Margin="5"
Theme="{StaticResource ProgressButtonInfo}"
Progress="{Binding Progress}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
<hc:ProgressButton Width="180"
Margin="5"
Theme="{StaticResource ProgressButtonWarning}"
Progress="{Binding Progress}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
<hc:ProgressButton Width="180"
Margin="5"
Theme="{StaticResource ProgressButtonDanger}"
Progress="{Binding Progress}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
</StackPanel>
<StackPanel Margin="16"
Spacing="0">
<ToggleButton Width="180"
Margin="5"
Theme="{StaticResource ToggleButtonLoading}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
<ToggleButton Width="180"
Margin="5"
Theme="{StaticResource ToggleButtonLoadingPrimary}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
<ToggleButton Width="180"
Margin="5"
Theme="{StaticResource ToggleButtonLoadingSuccess}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
<ToggleButton Width="180"
Margin="5"
Theme="{StaticResource ToggleButtonLoadingInfo}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
<ToggleButton Width="180"
Margin="5"
Theme="{StaticResource ToggleButtonLoadingWarning}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
<ToggleButton Width="180"
Margin="5"
Theme="{StaticResource ToggleButtonLoadingDanger}"
IsChecked="{Binding IsUploading, Mode=TwoWay}"
Content="{Binding UploadContent}" />
</StackPanel>
</WrapPanel>
</ScrollViewer>
</UserControl>
@@ -0,0 +1,114 @@
using System;
using Avalonia;
using Avalonia.Threading;
using HandyControlDemo.Properties.Langs;
namespace HandyControlDemo.UserControl;
public partial class ProgressButtonDemo : Avalonia.Controls.UserControl
{
private readonly DispatcherTimer _timer;
private int _progress;
private bool _isUploading;
public static readonly DirectProperty<ProgressButtonDemo, int> ProgressProperty =
AvaloniaProperty.RegisterDirect<ProgressButtonDemo, int>(nameof(Progress), o => o.Progress, (o, v) => o.Progress = v);
public static readonly DirectProperty<ProgressButtonDemo, bool> IsUploadingProperty =
AvaloniaProperty.RegisterDirect<ProgressButtonDemo, bool>(nameof(IsUploading), o => o.IsUploading, (o, v) => o.IsUploading = v);
public static readonly DirectProperty<ProgressButtonDemo, string> UploadContentProperty =
AvaloniaProperty.RegisterDirect<ProgressButtonDemo, string>(nameof(UploadContent), o => o.UploadContent);
public ProgressButtonDemo()
{
InitializeComponent();
DataContext = this;
_timer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(200)
};
_timer.Tick += Timer_Tick;
}
public int Progress
{
get => _progress;
set
{
if (_progress == value)
{
return;
}
var oldValue = _progress;
_progress = value;
RaisePropertyChanged(ProgressProperty, oldValue, value);
}
}
public bool IsUploading
{
get => _isUploading;
set
{
if (_isUploading == value)
{
return;
}
var oldValue = _isUploading;
var oldUploadContent = UploadContent;
_isUploading = value;
RaisePropertyChanged(IsUploadingProperty, oldValue, value);
RaisePropertyChanged(UploadContentProperty, oldUploadContent, UploadContent);
if (_isUploading)
{
if (!_timer.IsEnabled)
{
_timer.Start();
}
}
else
{
if (_timer.IsEnabled)
{
_timer.Stop();
}
if (Progress != 0)
{
Progress = 0;
}
}
}
}
public string UploadContent
{
get
{
var values = Lang.UploadStr.Split(';');
if (values.Length < 2)
{
return Lang.UploadStr;
}
return (IsUploading ? values[1] : values[0]).Trim();
}
}
private void Timer_Tick(object? sender, EventArgs e)
{
Progress++;
if (Progress >= 100)
{
Progress = 0;
IsUploading = false;
}
}
}
@@ -0,0 +1,144 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:vm="clr-namespace:HandyControlDemo.ViewModel"
x:Class="HandyControlDemo.UserControl.SearchBarDemo"
DataContext="{Binding InputElementDemo, Source={x:Static vm:ViewModelLocator.Instance}}"
Background="{DynamicResource RegionBrush}">
<TransitioningContentControl>
<ScrollViewer>
<hc:UniformSpacingPanel Spacing="32"
Margin="32"
ChildWrapping="Wrap">
<StackPanel Spacing="16">
<hc:SearchBar SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar IsEnabled="False" />
<hc:SearchBar Theme="{StaticResource SearchBarExtend}"
hc:TitleElement.Title="This is the title"
SearchStarted="SearchBar_OnSearchStarted"
Margin="0,16,0,0" />
<hc:SearchBar Theme="{StaticResource SearchBarExtend}"
Watermark="Please enter content"
hc:TitleElement.Title="This item must be filled in"
hc:InfoElement.Necessary="True"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarExtend}"
Width="380"
hc:TitleElement.TitleWidth="120"
hc:TitleElement.TitlePlacement="Left"
hc:TitleElement.Title="The title is on the left"
Watermark="Please enter content"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarExtend}"
Width="380"
hc:TitleElement.TitleWidth="120"
hc:TitleElement.TitlePlacement="Left"
hc:TitleElement.Title="The title is on the left"
Watermark="Please enter content"
hc:InfoElement.Necessary="True"
SearchStarted="SearchBar_OnSearchStarted" />
</StackPanel>
<StackPanel Spacing="16">
<hc:SearchBar Theme="{StaticResource SearchBarPlus}"
hc:InfoElement.ShowClearButton="True"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarPlus}"
IsEnabled="False" />
<hc:SearchBar Theme="{StaticResource SearchBarPlus}"
hc:InfoElement.ShowClearButton="True"
hc:TitleElement.Title="This is the title"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarPlus}"
Watermark="please enter email"
Text="{Binding Email1, UpdateSourceTrigger=PropertyChanged}"
hc:TitleElement.Title="This item must be filled in"
hc:InfoElement.Necessary="True"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarPlus}"
Width="380"
hc:TitleElement.TitleWidth="120"
hc:TitleElement.TitlePlacement="Left"
hc:TitleElement.Title="The title is on the left"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarPlus}"
Width="380"
hc:InfoElement.ShowClearButton="True"
hc:TitleElement.TitleWidth="120"
hc:TitleElement.TitlePlacement="Left"
hc:TitleElement.Title="The title is on the left"
Watermark="Please enter content"
hc:InfoElement.Necessary="True"
SearchStarted="SearchBar_OnSearchStarted" />
</StackPanel>
<StackPanel Spacing="16">
<hc:SearchBar Theme="{StaticResource SearchBar.Small}"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBar.Small}"
IsEnabled="False" />
<hc:SearchBar Theme="{StaticResource SearchBarExtend.Small}"
hc:TitleElement.Title="This is the title"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarExtend.Small}"
Watermark="Please enter content"
hc:TitleElement.Title="This item must be filled in"
hc:InfoElement.Necessary="True"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarExtend.Small}"
Width="380"
hc:TitleElement.TitleWidth="120"
hc:TitleElement.TitlePlacement="Left"
hc:TitleElement.Title="The title is on the left"
Watermark="Please enter content"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarExtend.Small}"
Width="380"
hc:TitleElement.TitleWidth="120"
hc:TitleElement.TitlePlacement="Left"
hc:TitleElement.Title="The title is on the left"
Watermark="Please enter content"
hc:InfoElement.Necessary="True"
SearchStarted="SearchBar_OnSearchStarted" />
</StackPanel>
<StackPanel Spacing="16">
<hc:SearchBar Theme="{StaticResource SearchBarPlus.Small}"
hc:InfoElement.ShowClearButton="True"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarPlus.Small}"
IsEnabled="False" />
<hc:SearchBar Theme="{StaticResource SearchBarPlus.Small}"
hc:InfoElement.ShowClearButton="True"
hc:TitleElement.Title="This is the title"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarPlus.Small}"
Watermark="please enter email"
Text="{Binding Email2, UpdateSourceTrigger=PropertyChanged}"
hc:TitleElement.Title="This item must be filled in"
hc:InfoElement.Necessary="True"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarPlus.Small}"
Width="380"
hc:TitleElement.TitleWidth="120"
hc:TitleElement.TitlePlacement="Left"
hc:TitleElement.Title="The title is on the left"
SearchStarted="SearchBar_OnSearchStarted" />
<hc:SearchBar Theme="{StaticResource SearchBarPlus.Small}"
Width="380"
hc:InfoElement.ShowClearButton="True"
hc:TitleElement.TitleWidth="120"
hc:TitleElement.TitlePlacement="Left"
hc:TitleElement.Title="The title is on the left"
Watermark="Please enter content"
hc:InfoElement.Necessary="True"
SearchStarted="SearchBar_OnSearchStarted" />
</StackPanel>
</hc:UniformSpacingPanel>
</ScrollViewer>
</TransitioningContentControl>
</UserControl>
@@ -0,0 +1,25 @@
using Avalonia.Interactivity;
using HandyControl.Controls;
using HandyControl.Data;
namespace HandyControlDemo.UserControl;
public partial class SearchBarDemo : Avalonia.Controls.UserControl
{
public SearchBarDemo()
{
InitializeComponent();
}
private void SearchBar_OnSearchStarted(object? sender, FunctionEventArgs<string?> e)
{
if (string.IsNullOrWhiteSpace(e.Info))
{
return;
}
var growlType = System.Type.GetType("HandyControl.Controls.Growl, HandyControl");
var method = growlType?.GetMethod("Info", [typeof(string), typeof(string)]);
method?.Invoke(null, [e.Info, string.Empty]);
}
}
@@ -0,0 +1,20 @@
using System;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Tools.Extension;
namespace HandyControlDemo.ViewModel;
public partial class InteractiveDialogViewModel : ObservableObject, IDialogResultable<string>
{
public Action CloseAction { get; set; }
[ObservableProperty]
private string _result;
[ObservableProperty]
private string _message;
[RelayCommand]
private void Close() => CloseAction?.Invoke();
}
@@ -0,0 +1,70 @@
using System.Threading.Tasks;
using Avalonia.Controls;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using HandyControlDemo.Data;
using HandyControlDemo.UserControl;
using HandyControlDemo.Window;
namespace HandyControlDemo.ViewModel;
public partial class DialogDemoViewModel : ObservableObject
{
[ObservableProperty]
private string _dialogResult;
[RelayCommand]
private void ShowText(Control? element)
{
if (element == null)
{
Dialog.Show(new TextDialog());
}
else
{
Dialog.Show(new TextDialog(), MessageToken.DialogContainer);
}
}
[RelayCommand]
private async Task ShowInteractiveDialog(bool withTimer)
{
if (!withTimer)
{
DialogResult = await Dialog.Show<InteractiveDialog>()
.Initialize<InteractiveDialogViewModel>(vm => vm.Message = DialogResult)
.GetResultAsync<string>();
}
else
{
await Dialog.Show<TextDialogWithTimer>(MessageToken.MainWindow).GetResultAsync<string>();
}
}
[RelayCommand]
private void NewWindow()
{
var window = new DialogDemoWindow();
window.Show();
}
[RelayCommand]
private void ShowWithToken(string token)
{
if (!string.IsNullOrEmpty(token))
{
Dialog.Show(new TextDialog(), token);
}
}
[RelayCommand]
private void CloseMainWindowDialog(string token)
{
if (!string.IsNullOrEmpty(token))
{
Dialog.Close(token);
}
}
}
@@ -21,6 +21,7 @@ public class ViewModelLocator
services.AddTransient<MainViewModel>();
services.AddTransient<InputElementDemoViewModel>();
services.AddTransient<CardDemoViewModel>();
services.AddTransient<DialogDemoViewModel>();
_serviceProvider = services.BuildServiceProvider();
}
@@ -30,4 +31,6 @@ public class ViewModelLocator
public InputElementDemoViewModel InputElementDemo => _serviceProvider.GetService<InputElementDemoViewModel>()!;
public CardDemoViewModel CardDemo => _serviceProvider.GetService<CardDemoViewModel>()!;
public DialogDemoViewModel DialogDemo => _serviceProvider.GetService<DialogDemoViewModel>()!;
}
@@ -0,0 +1,29 @@
<Window x:Class="HandyControlDemo.Window.DialogDemoWindow"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:vm="clr-namespace:HandyControlDemo.ViewModel"
xmlns:data="clr-namespace:HandyControlDemo.Data"
x:DataType="vm:DialogDemoViewModel"
DataContext="{Binding DialogDemo, Source={x:Static vm:ViewModelLocator.Instance}}"
Width="800"
Height="500"
Background="{DynamicResource SecondaryRegionBrush}">
<TransitioningContentControl>
<hc:UniformSpacingPanel Margin="32"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Orientation="Vertical"
Spacing="10">
<Button Content="ShowInCurrentWindow"
Command="{Binding ShowWithTokenCommand}"
CommandParameter="{Binding $parent[Window].DialogToken}" />
<Button Content="ShowInMainWindow"
Command="{Binding ShowWithTokenCommand}"
CommandParameter="{x:Static data:MessageToken.MainWindow}" />
<Button Content="CloseMainWindowDialog"
Command="{Binding CloseMainWindowDialogCommand}"
CommandParameter="{x:Static data:MessageToken.MainWindow}" />
</hc:UniformSpacingPanel>
</TransitioningContentControl>
</Window>
@@ -0,0 +1,19 @@
using System;
using Avalonia.Controls;
using HandyControl.Controls;
using HandyControlDemo.Data;
namespace HandyControlDemo.Window;
public partial class DialogDemoWindow : Avalonia.Controls.Window
{
public string DialogToken { get; }
public DialogDemoWindow()
{
InitializeComponent();
DialogToken = $"{MessageToken.DialogDemoWindow}+{DateTime.Now:yyyyMMddHHmmssfff}";
Dialog.SetToken(this, DialogToken);
}
}
@@ -0,0 +1,26 @@
using Avalonia;
using Avalonia.Controls.Primitives;
using Avalonia.Styling;
namespace HandyControl.Controls;
public class ProgressButton : ToggleButton
{
public static readonly StyledProperty<ControlTheme?> ProgressThemeProperty =
AvaloniaProperty.Register<ProgressButton, ControlTheme?>(nameof(ProgressTheme));
public static readonly StyledProperty<double> ProgressProperty =
AvaloniaProperty.Register<ProgressButton, double>(nameof(Progress));
public ControlTheme? ProgressTheme
{
get => GetValue(ProgressThemeProperty);
set => SetValue(ProgressThemeProperty, value);
}
public double Progress
{
get => GetValue(ProgressProperty);
set => SetValue(ProgressProperty, value);
}
}
@@ -0,0 +1,211 @@
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
using HandyControl.Tools;
namespace HandyControl.Controls;
[TemplatePart("PART_BackElement", typeof(Border))]
public class Dialog : ContentControl
{
private const string BackElement = "PART_BackElement";
private string? _token;
private Border? _backElement;
private Panel? _hostPanel;
private static readonly ControlTokenManager<Control> TokenManager = new();
private static readonly Dictionary<string, Dialog> DialogDict = new();
public static readonly StyledProperty<bool> IsClosedProperty =
AvaloniaProperty.Register<Dialog, bool>(nameof(IsClosed));
public bool IsClosed
{
get => GetValue(IsClosedProperty);
internal set => SetValue(IsClosedProperty, value);
}
public static readonly AttachedProperty<bool> MaskCanCloseProperty =
AvaloniaProperty.RegisterAttached<Dialog, AvaloniaObject, bool>("MaskCanClose", false);
public static void SetMaskCanClose(AvaloniaObject element, bool value) =>
element.SetValue(MaskCanCloseProperty, value);
public static bool GetMaskCanClose(AvaloniaObject element) =>
element.GetValue(MaskCanCloseProperty);
public static readonly StyledProperty<IBrush?> MaskBrushProperty =
AvaloniaProperty.Register<Dialog, IBrush?>(nameof(MaskBrush));
public IBrush? MaskBrush
{
get => GetValue(MaskBrushProperty);
set => SetValue(MaskBrushProperty, value);
}
public static readonly AttachedProperty<string?> TokenProperty =
AvaloniaProperty.RegisterAttached<Dialog, AvaloniaObject, string?>("Token");
static Dialog()
{
TokenProperty.Changed.AddClassHandler<AvaloniaObject>(TokenManager.OnTokenChanged);
}
public static void SetToken(AvaloniaObject element, string? value) =>
element.SetValue(TokenProperty, value);
public static string? GetToken(AvaloniaObject element) =>
element.GetValue(TokenProperty);
public static Dialog Show<T>(string? token = null) where T : new() => Show(new T(), token);
public static Dialog Show(object content, string? token = null)
{
var dialog = new Dialog
{
_token = token,
Content = content
};
if (string.IsNullOrEmpty(token))
{
var window = GetActiveWindow();
if (window != null)
{
ShowOnWindow(dialog, window);
}
}
else
{
Close(token);
DialogDict[token] = dialog;
if (TokenManager.TryGetControl(token, out var ctrl) && ctrl != null)
{
if (ctrl is Window window)
{
ShowOnWindow(dialog, window);
}
else
{
var panel = FindDialogContainer(ctrl);
if (panel != null)
{
dialog._hostPanel = panel;
dialog.IsClosed = false;
dialog.Width = panel.Bounds.Width;
dialog.Height = panel.Bounds.Height;
panel.Children.Add(dialog);
panel.InvalidateMeasure();
}
else
{
var win = GetActiveWindow();
if (win != null)
ShowOnWindow(dialog, win);
}
}
}
}
return dialog;
}
private static void ShowOnWindow(Dialog dialog, Window window)
{
var overlay = OverlayLayer.GetOverlayLayer(window);
if (overlay == null) return;
var size = overlay.Bounds.Size;
if (size.Width <= 0 || size.Height <= 0)
{
var topLevel = TopLevel.GetTopLevel(overlay);
if (topLevel != null)
size = topLevel.ClientSize;
}
dialog._hostPanel = overlay;
dialog.IsClosed = false;
dialog.Width = size.Width;
dialog.Height = size.Height;
overlay.Children.Add(dialog);
void OnOverlayResized(object? sender, SizeChangedEventArgs e)
{
if (dialog._hostPanel == null) return;
dialog.Width = e.NewSize.Width;
dialog.Height = e.NewSize.Height;
}
overlay.SizeChanged += OnOverlayResized;
}
public static void Close(string? token)
{
if (!string.IsNullOrEmpty(token) && DialogDict.TryGetValue(token, out var dialog))
{
dialog.Close();
}
}
public void Close()
{
if (_hostPanel == null) return;
_hostPanel.Children.Remove(this);
_hostPanel = null;
IsClosed = true;
if (!string.IsNullOrEmpty(_token))
{
DialogDict.Remove(_token);
}
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_backElement = e.NameScope.Find<Border>(BackElement);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (e.InitialPressMouseButton == MouseButton.Left &&
GetMaskCanClose(this) && _backElement != null && _backElement.IsPointerOver)
{
Close();
}
}
private static DialogContainer? FindDialogContainer(Visual root)
{
foreach (var child in root.GetVisualChildren())
{
if (child is DialogContainer found)
return found;
var nested = FindDialogContainer(child);
if (nested != null)
return nested;
}
return null;
}
private static Window? GetActiveWindow()
{
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
return desktop.Windows.FirstOrDefault(w => w.IsActive) ?? desktop.MainWindow;
}
return null;
}
}
@@ -0,0 +1,8 @@
using Avalonia.Controls;
namespace HandyControl.Controls;
/// <summary>
/// A panel that can host Dialog overlays when targeted by a matching token.
/// </summary>
public class DialogContainer : Panel;
@@ -0,0 +1,232 @@
using System;
using System.Collections.Generic;
using System.IO;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Platform.Storage;
namespace HandyControl.Controls;
/// <summary>
/// A control that allows selecting an image file via a file picker dialog.
/// Displays the selected image preview inside a configurable frame.
/// </summary>
public class ImageSelector : TemplatedControl
{
public static readonly RoutedEvent<RoutedEventArgs> ImageSelectedEvent =
RoutedEvent.Register<ImageSelector, RoutedEventArgs>(nameof(ImageSelected), RoutingStrategies.Bubble);
public static readonly RoutedEvent<RoutedEventArgs> ImageUnselectedEvent =
RoutedEvent.Register<ImageSelector, RoutedEventArgs>(nameof(ImageUnselected), RoutingStrategies.Bubble);
public event EventHandler<RoutedEventArgs>? ImageSelected
{
add => AddHandler(ImageSelectedEvent, value);
remove => RemoveHandler(ImageSelectedEvent, value);
}
public event EventHandler<RoutedEventArgs>? ImageUnselected
{
add => AddHandler(ImageUnselectedEvent, value);
remove => RemoveHandler(ImageUnselectedEvent, value);
}
static ImageSelector()
{
FocusableProperty.OverrideDefaultValue<ImageSelector>(true);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
{
SwitchImage();
}
}
private async void SwitchImage()
{
if (!HasValue)
{
var topLevel = TopLevel.GetTopLevel(this);
if (topLevel == null) return;
var patterns = ParseFilterPatterns(Filter);
var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
AllowMultiple = false,
FileTypeFilter =
[
new FilePickerFileType("Images") { Patterns = patterns },
],
});
if (files.Count > 0)
{
var file = files[0];
var localPath = file.TryGetLocalPath();
HasValue = true;
try
{
await using var stream = await file.OpenReadAsync();
var bitmap = new Bitmap(stream);
PreviewBrush = new ImageBrush(bitmap) { Stretch = Stretch };
}
catch
{
PreviewBrush = null;
}
if (localPath != null)
Uri = new Uri(localPath);
ToolTip.SetTip(this, file.Name);
RaiseEvent(new RoutedEventArgs(ImageSelectedEvent));
}
}
else
{
HasValue = false;
PreviewBrush = null;
Uri = null;
ToolTip.SetTip(this, null);
RaiseEvent(new RoutedEventArgs(ImageUnselectedEvent));
}
}
// ── Properties ──
public static readonly StyledProperty<Stretch> StretchProperty =
AvaloniaProperty.Register<ImageSelector, Stretch>(nameof(Stretch));
public Stretch Stretch
{
get => GetValue(StretchProperty);
set => SetValue(StretchProperty, value);
}
public static readonly DirectProperty<ImageSelector, Uri?> UriProperty =
AvaloniaProperty.RegisterDirect<ImageSelector, Uri?>(nameof(Uri), o => o.Uri);
private Uri? _uri;
public Uri? Uri
{
get => _uri;
private set => SetAndRaise(UriProperty, ref _uri, value);
}
public static readonly DirectProperty<ImageSelector, IBrush?> PreviewBrushProperty =
AvaloniaProperty.RegisterDirect<ImageSelector, IBrush?>(nameof(PreviewBrush), o => o.PreviewBrush);
private IBrush? _previewBrush;
public IBrush? PreviewBrush
{
get => _previewBrush;
private set => SetAndRaise(PreviewBrushProperty, ref _previewBrush, value);
}
public static readonly StyledProperty<double> StrokeThicknessProperty =
AvaloniaProperty.Register<ImageSelector, double>(nameof(StrokeThickness), 1.0);
public double StrokeThickness
{
get => GetValue(StrokeThicknessProperty);
set => SetValue(StrokeThicknessProperty, value);
}
public static readonly StyledProperty<Avalonia.Collections.AvaloniaList<double>?> StrokeDashArrayProperty =
AvaloniaProperty.Register<ImageSelector, Avalonia.Collections.AvaloniaList<double>?>(nameof(StrokeDashArray));
public Avalonia.Collections.AvaloniaList<double>? StrokeDashArray
{
get => GetValue(StrokeDashArrayProperty);
set => SetValue(StrokeDashArrayProperty, value);
}
public static readonly StyledProperty<string> DefaultExtProperty =
AvaloniaProperty.Register<ImageSelector, string>(nameof(DefaultExt), ".jpg");
public string DefaultExt
{
get => GetValue(DefaultExtProperty);
set => SetValue(DefaultExtProperty, value);
}
public static readonly StyledProperty<string> FilterProperty =
AvaloniaProperty.Register<ImageSelector, string>(nameof(Filter), "(.jpg)|*.jpg|(.png)|*.png");
public string Filter
{
get => GetValue(FilterProperty);
set => SetValue(FilterProperty, value);
}
/// <summary>
/// Parses a WPF-style filter string like "(.jpg)|*.jpg|(.png)|*.png"
/// into individual glob patterns for the cross-platform file picker.
/// </summary>
private static List<string> ParseFilterPatterns(string? filter)
{
var patterns = new List<string>();
if (string.IsNullOrWhiteSpace(filter))
{
// Sensible cross-platform defaults with case variations
patterns.AddRange(["*.jpg", "*.jpeg", "*.png", "*.bmp", "*.gif"]);
patterns.AddRange(["*.JPG", "*.JPEG", "*.PNG", "*.BMP", "*.GIF"]);
return patterns;
}
// WPF format: "Description|*.ext|Description|*.ext"
var parts = filter.Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
foreach (var part in parts)
{
// Skip display-name segments (e.g. "(.jpg)"); only keep pattern segments
if (part.Contains('*') || part.Contains('?'))
{
// Split multi-pattern entries like "*.jpg;*.png"
foreach (var p in part.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var trimmed = p.Trim();
if (!string.IsNullOrEmpty(trimmed) && !patterns.Contains(trimmed))
{
patterns.Add(trimmed);
// Add uppercase variant for case-sensitive platforms (macOS)
var upper = trimmed.ToUpperInvariant();
if (upper != trimmed && !patterns.Contains(upper))
patterns.Add(upper);
}
}
}
}
// Fallback if parsing produced nothing
if (patterns.Count == 0)
{
patterns.AddRange(["*.jpg", "*.jpeg", "*.png", "*.bmp", "*.gif",
"*.JPG", "*.JPEG", "*.PNG", "*.BMP", "*.GIF"]);
}
return patterns;
}
public static readonly DirectProperty<ImageSelector, bool> HasValueProperty =
AvaloniaProperty.RegisterDirect<ImageSelector, bool>(nameof(HasValue), o => o.HasValue);
private bool _hasValue;
public bool HasValue
{
get => _hasValue;
private set => SetAndRaise(HasValueProperty, ref _hasValue, value);
}
}
@@ -0,0 +1,469 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
namespace HandyControl.Controls;
[TemplatePart(Name = ElementPanel, Type = typeof(Panel))]
public class PinBox : TemplatedControl
{
private const string ElementPanel = "PART_Panel";
private const int MinLength = 4;
public static readonly StyledProperty<char> PasswordCharProperty =
AvaloniaProperty.Register<PinBox, char>(nameof(PasswordChar), '●');
public static readonly StyledProperty<int> LengthProperty =
AvaloniaProperty.Register<PinBox, int>(nameof(Length), MinLength);
public static readonly StyledProperty<Thickness> ItemMarginProperty =
AvaloniaProperty.Register<PinBox, Thickness>(nameof(ItemMargin), new Thickness(4, 0));
public static readonly StyledProperty<double> ItemWidthProperty =
AvaloniaProperty.Register<PinBox, double>(nameof(ItemWidth), 32d);
public static readonly StyledProperty<double> ItemHeightProperty =
AvaloniaProperty.Register<PinBox, double>(nameof(ItemHeight), 32d);
public static readonly StyledProperty<IBrush?> SelectionBrushProperty =
AvaloniaProperty.Register<PinBox, IBrush?>(nameof(SelectionBrush));
public static readonly StyledProperty<IBrush?> CaretBrushProperty =
AvaloniaProperty.Register<PinBox, IBrush?>(nameof(CaretBrush));
public static readonly StyledProperty<bool> IsSafeEnabledProperty =
AvaloniaProperty.Register<PinBox, bool>(nameof(IsSafeEnabled), true);
public static readonly StyledProperty<string?> UnsafePasswordProperty =
AvaloniaProperty.Register<PinBox, string?>(nameof(UnsafePassword), defaultBindingMode: Avalonia.Data.BindingMode.TwoWay);
public static readonly StyledProperty<string?> PasswordProperty =
AvaloniaProperty.Register<PinBox, string?>(nameof(Password));
public static readonly RoutedEvent<RoutedEventArgs> CompletedEvent =
RoutedEvent.Register<PinBox, RoutedEventArgs>(nameof(Completed), RoutingStrategies.Bubble);
private Panel? _panel;
private readonly List<TextBox> _textBoxes = [];
private bool _isInternalAction;
private int _inputIndex;
private string _cachedPassword = string.Empty;
static PinBox()
{
FocusableProperty.OverrideDefaultValue<PinBox>(false);
LengthProperty.Changed.AddClassHandler<PinBox>((pinBox, e) =>
{
var newLength = e.GetNewValue<int>();
if (newLength < MinLength)
{
pinBox.SetCurrentValue(LengthProperty, MinLength);
return;
}
pinBox.UpdateItems();
});
ItemMarginProperty.Changed.AddClassHandler<PinBox>((pinBox, _) => pinBox.ApplyItemVisualProperties());
ItemWidthProperty.Changed.AddClassHandler<PinBox>((pinBox, _) => pinBox.ApplyItemVisualProperties());
ItemHeightProperty.Changed.AddClassHandler<PinBox>((pinBox, _) => pinBox.ApplyItemVisualProperties());
PasswordCharProperty.Changed.AddClassHandler<PinBox>((pinBox, _) => pinBox.ApplyItemVisualProperties());
ForegroundProperty.Changed.AddClassHandler<PinBox>((pinBox, _) => pinBox.ApplyItemVisualProperties());
SelectionBrushProperty.Changed.AddClassHandler<PinBox>((pinBox, _) => pinBox.ApplyItemVisualProperties());
CaretBrushProperty.Changed.AddClassHandler<PinBox>((pinBox, _) => pinBox.ApplyItemVisualProperties());
PasswordProperty.Changed.AddClassHandler<PinBox>((pinBox, e) =>
{
if (pinBox._isInternalAction)
{
return;
}
pinBox.ApplyPasswordToItems(e.GetNewValue<string?>() ?? string.Empty);
pinBox.UpdateUnsafePassword();
});
UnsafePasswordProperty.Changed.AddClassHandler<PinBox>((pinBox, e) =>
{
if (pinBox._isInternalAction || pinBox.IsSafeEnabled)
{
return;
}
pinBox.SetCurrentValue(PasswordProperty, e.GetNewValue<string?>() ?? string.Empty);
});
IsSafeEnabledProperty.Changed.AddClassHandler<PinBox>((pinBox, e) => pinBox.OnIsSafeEnabledChanged(e.GetNewValue<bool>()));
}
public event EventHandler<RoutedEventArgs> Completed
{
add => AddHandler(CompletedEvent, value);
remove => RemoveHandler(CompletedEvent, value);
}
public char PasswordChar
{
get => GetValue(PasswordCharProperty);
set => SetValue(PasswordCharProperty, value);
}
public int Length
{
get => GetValue(LengthProperty);
set => SetValue(LengthProperty, value < MinLength ? MinLength : value);
}
public Thickness ItemMargin
{
get => GetValue(ItemMarginProperty);
set => SetValue(ItemMarginProperty, value);
}
public double ItemWidth
{
get => GetValue(ItemWidthProperty);
set => SetValue(ItemWidthProperty, value);
}
public double ItemHeight
{
get => GetValue(ItemHeightProperty);
set => SetValue(ItemHeightProperty, value);
}
public IBrush? SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
public IBrush? CaretBrush
{
get => GetValue(CaretBrushProperty);
set => SetValue(CaretBrushProperty, value);
}
public bool IsSafeEnabled
{
get => GetValue(IsSafeEnabledProperty);
set => SetValue(IsSafeEnabledProperty, value);
}
public string UnsafePassword
{
get => GetValue(UnsafePasswordProperty) ?? string.Empty;
set => SetValue(UnsafePasswordProperty, value);
}
public string Password
{
get => GetValue(PasswordProperty) ?? string.Empty;
set => SetValue(PasswordProperty, value);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_panel = e.NameScope.Find<Panel>(ElementPanel);
UpdateItems();
var initialPassword = string.IsNullOrEmpty(Password) ? _cachedPassword : Password;
if (!string.IsNullOrEmpty(initialPassword))
{
ApplyPasswordToItems(initialPassword);
}
OnIsSafeEnabledChanged(IsSafeEnabled);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
FocusPasswordBox();
}
private void FocusPasswordBox()
{
if (_textBoxes.Count == 0)
{
return;
}
if (_textBoxes.Any(box => box.IsFocused))
{
return;
}
var index = Math.Clamp(_inputIndex, 0, _textBoxes.Count - 1);
_textBoxes[index].Focus();
_textBoxes[index].SelectAll();
}
private void UpdateItems()
{
if (_panel == null)
{
return;
}
_panel.Children.Clear();
_textBoxes.Clear();
_inputIndex = 0;
var length = Math.Max(Length, MinLength);
for (var i = 0; i < length; i++)
{
var textBox = CreateTextBox();
_textBoxes.Add(textBox);
_panel.Children.Add(textBox);
}
ApplyItemVisualProperties();
}
private TextBox CreateTextBox()
{
var textBox = new TextBox
{
MaxLength = 1,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
TextAlignment = TextAlignment.Center,
Padding = default
};
textBox.TextChanged += TextBoxOnTextChanged;
textBox.GotFocus += TextBoxOnGotFocus;
textBox.AddHandler(InputElement.KeyDownEvent, TextBoxOnKeyDown, RoutingStrategies.Tunnel, handledEventsToo: true);
return textBox;
}
private void ApplyItemVisualProperties()
{
foreach (var textBox in _textBoxes)
{
textBox.Margin = ItemMargin;
textBox.Width = ItemWidth;
textBox.Height = ItemHeight;
textBox.PasswordChar = PasswordChar;
textBox.Foreground = Foreground;
textBox.SelectionBrush = SelectionBrush;
textBox.CaretBrush = CaretBrush;
}
}
private void TextBoxOnGotFocus(object? sender, GotFocusEventArgs e)
{
if (sender is not TextBox textBox)
{
return;
}
_inputIndex = _textBoxes.IndexOf(textBox);
textBox.SelectAll();
}
private void TextBoxOnTextChanged(object? sender, TextChangedEventArgs e)
{
if (_isInternalAction || sender is not TextBox textBox)
{
return;
}
var index = _textBoxes.IndexOf(textBox);
if (index < 0)
{
return;
}
if (!string.IsNullOrEmpty(textBox.Text) && textBox.Text!.Length > 1)
{
_isInternalAction = true;
textBox.Text = textBox.Text[^1].ToString();
_isInternalAction = false;
}
_inputIndex = index;
if (!string.IsNullOrEmpty(textBox.Text))
{
MoveToNext(index);
}
SyncPasswordFromItems();
if (_textBoxes.Count > 0 && _textBoxes.All(item => !string.IsNullOrEmpty(item.Text)))
{
RaiseEvent(new RoutedEventArgs(CompletedEvent, this));
Dispatcher.UIThread.Post(() => TopLevel.GetTopLevel(this)?.FocusManager?.ClearFocus(), DispatcherPriority.Background);
}
}
private void TextBoxOnKeyDown(object? sender, KeyEventArgs e)
{
if (sender is not TextBox textBox)
{
return;
}
var index = _textBoxes.IndexOf(textBox);
if (index < 0)
{
return;
}
switch (e.Key)
{
case Key.Left:
MoveFocus(Math.Max(index - 1, 0));
e.Handled = true;
break;
case Key.Right:
MoveFocus(Math.Min(index + 1, _textBoxes.Count - 1));
e.Handled = true;
break;
case Key.Back:
HandleBackspace(index, textBox);
e.Handled = true;
break;
case Key.Delete:
HandleDelete(index, textBox);
e.Handled = true;
break;
}
}
private void HandleBackspace(int index, TextBox textBox)
{
var target = Math.Max(index - 1, 0);
_isInternalAction = true;
if (string.IsNullOrEmpty(textBox.Text) && index > 0)
{
_textBoxes[target].Clear();
}
else
{
textBox.Clear();
}
_isInternalAction = false;
MoveFocusDeferred(target);
SyncPasswordFromItems();
}
private void HandleDelete(int index, TextBox textBox)
{
var target = Math.Max(index - 1, 0);
_isInternalAction = true;
if (string.IsNullOrEmpty(textBox.Text) && index > 0)
{
_textBoxes[target].Clear();
}
else
{
textBox.Clear();
}
_isInternalAction = false;
MoveFocusDeferred(target);
SyncPasswordFromItems();
}
private void MoveToNext(int index)
{
if (index >= _textBoxes.Count - 1)
{
_inputIndex = _textBoxes.Count - 1;
return;
}
MoveFocus(index + 1);
}
private void MoveFocus(int index)
{
if (_textBoxes.Count == 0)
{
return;
}
_inputIndex = Math.Clamp(index, 0, _textBoxes.Count - 1);
var textBox = _textBoxes[_inputIndex];
textBox.Focus();
textBox.SelectAll();
}
private void MoveFocusDeferred(int index)
{
_inputIndex = Math.Clamp(index, 0, Math.Max(_textBoxes.Count - 1, 0));
Dispatcher.UIThread.Post(() => MoveFocus(_inputIndex), DispatcherPriority.Input);
}
private void SyncPasswordFromItems()
{
var password = string.Concat(_textBoxes.Select(box => box.Text ?? string.Empty));
_cachedPassword = password;
_isInternalAction = true;
SetCurrentValue(PasswordProperty, password);
_isInternalAction = false;
UpdateUnsafePassword();
}
private void ApplyPasswordToItems(string password)
{
_cachedPassword = password;
if (_textBoxes.Count == 0)
{
return;
}
_isInternalAction = true;
var limited = password.Length > _textBoxes.Count ? password[.._textBoxes.Count] : password;
for (var i = 0; i < _textBoxes.Count; i++)
{
_textBoxes[i].Text = i < limited.Length ? limited[i].ToString() : string.Empty;
}
_isInternalAction = false;
_inputIndex = Math.Min(limited.Length, _textBoxes.Count - 1);
}
private void OnIsSafeEnabledChanged(bool isSafeEnabled)
{
if (isSafeEnabled)
{
_isInternalAction = true;
SetCurrentValue(UnsafePasswordProperty, string.Empty);
_isInternalAction = false;
return;
}
UpdateUnsafePassword();
}
private void UpdateUnsafePassword()
{
_isInternalAction = true;
SetCurrentValue(UnsafePasswordProperty, IsSafeEnabled ? string.Empty : (_textBoxes.Count == 0 ? _cachedPassword : string.Concat(_textBoxes.Select(item => item.Text ?? string.Empty))));
_isInternalAction = false;
}
}
@@ -0,0 +1,129 @@
using System;
using System.Windows.Input;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using HandyControl.Data;
namespace HandyControl.Controls;
[TemplatePart(Name = ElementSearchButton, Type = typeof(Button))]
public class SearchBar : TextBox
{
private const string ElementSearchButton = "PART_SearchButton";
public static readonly RoutedEvent<FunctionEventArgs<string?>> SearchStartedEvent =
RoutedEvent.Register<SearchBar, FunctionEventArgs<string?>>(nameof(SearchStarted), RoutingStrategies.Bubble);
public static readonly StyledProperty<bool> IsRealTimeProperty =
AvaloniaProperty.Register<SearchBar, bool>(nameof(IsRealTime));
public static readonly StyledProperty<ICommand?> CommandProperty =
AvaloniaProperty.Register<SearchBar, ICommand?>(nameof(Command));
public static readonly StyledProperty<object?> CommandParameterProperty =
AvaloniaProperty.Register<SearchBar, object?>(nameof(CommandParameter));
public static readonly StyledProperty<IInputElement?> CommandTargetProperty =
AvaloniaProperty.Register<SearchBar, IInputElement?>(nameof(CommandTarget));
private Button? _searchButton;
static SearchBar()
{
TextProperty.Changed.AddClassHandler<SearchBar>((searchBar, _) =>
{
if (searchBar.IsRealTime)
{
searchBar.OnSearchStarted();
}
});
}
public event EventHandler<FunctionEventArgs<string?>> SearchStarted
{
add => AddHandler(SearchStartedEvent, value);
remove => RemoveHandler(SearchStartedEvent, value);
}
public bool IsRealTime
{
get => GetValue(IsRealTimeProperty);
set => SetValue(IsRealTimeProperty, value);
}
public ICommand? Command
{
get => GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
public object? CommandParameter
{
get => GetValue(CommandParameterProperty);
set => SetValue(CommandParameterProperty, value);
}
public IInputElement? CommandTarget
{
get => GetValue(CommandTargetProperty);
set => SetValue(CommandTargetProperty, value);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (_searchButton != null)
{
_searchButton.Click -= SearchButtonOnClick;
}
_searchButton = e.NameScope.Find<Button>(ElementSearchButton);
if (_searchButton != null)
{
_searchButton.Click += SearchButtonOnClick;
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Key == Key.Enter)
{
OnSearchStarted();
e.Handled = true;
}
}
private void SearchButtonOnClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
OnSearchStarted();
}
private void OnSearchStarted()
{
RaiseEvent(new FunctionEventArgs<string?>(SearchStartedEvent, this)
{
Info = Text
});
var command = Command;
if (command == null)
{
return;
}
var parameter = CommandParameter ?? Text;
if (!command.CanExecute(parameter))
{
return;
}
command.Execute(parameter);
}
}
@@ -58,6 +58,8 @@ public class LoadingCircle : LoadingBase
var dotDelayTime = DotDelayTime;
var needHidden = NeedHidden;
var dotOffset = DotOffSet;
var totalSeconds = dotSpeed + 0.4d;
var visibleCue = dotSpeed / totalSeconds;
if (dotCount < 1) return;
PrivateCanvas.Children.Clear();
@@ -73,20 +75,21 @@ public class LoadingCircle : LoadingBase
var rotateAnimation = new Animation
{
Duration = TimeSpan.FromSeconds(dotSpeed),
Duration = TimeSpan.FromSeconds(totalSeconds),
Delay = TimeSpan.FromMilliseconds(dotDelayTime * i),
IterationCount = IterationCount.Infinite,
FillMode = FillMode.Forward,
Easing = new LinearEasing(),
Children =
{
BuildAngleFrame(0d / 7d, 0 + subAngle, null),
BuildAngleFrame(0.75d / 7d, 180 + subAngle, EaseOutSpline),
BuildAngleFrame(2.75d / 7d, 180 + dotOffset + subAngle, null),
BuildAngleFrame(3.5d / 7d, 360 + subAngle, EaseInSpline),
BuildAngleFrame(4.25d / 7d, 540 + subAngle, EaseOutSpline),
BuildAngleFrame(6.25d / 7d, 540 + dotOffset + subAngle, null),
BuildAngleFrame(1d, 720 + subAngle, EaseInSpline),
BuildAngleFrame(0d, 0 + subAngle, null),
BuildAngleFrame((dotSpeed * (0.75d / 7d)) / totalSeconds, 180 + subAngle, EaseOutSpline),
BuildAngleFrame((dotSpeed * (2.75d / 7d)) / totalSeconds, 180 + dotOffset + subAngle, null),
BuildAngleFrame((dotSpeed * (3.5d / 7d)) / totalSeconds, 360 + subAngle, EaseInSpline),
BuildAngleFrame((dotSpeed * (4.25d / 7d)) / totalSeconds, 540 + subAngle, EaseOutSpline),
BuildAngleFrame((dotSpeed * (6.25d / 7d)) / totalSeconds, 540 + dotOffset + subAngle, null),
BuildAngleFrame(visibleCue, 720 + subAngle, EaseInSpline),
BuildAngleFrame(1d, 720 + subAngle, null),
}
};
@@ -96,10 +99,7 @@ public class LoadingCircle : LoadingBase
if (needHidden)
{
var totalSeconds = dotSpeed + 0.4d;
var visibleCue = dotSpeed / totalSeconds;
var opacityAnimation = new Animation
var visibleAnimation = new Animation
{
Duration = TimeSpan.FromSeconds(totalSeconds),
Delay = TimeSpan.FromMilliseconds(dotDelayTime * i),
@@ -111,29 +111,29 @@ public class LoadingCircle : LoadingBase
new KeyFrame
{
Cue = new Cue(0d),
Setters = { new Setter(Visual.OpacityProperty, 1d) }
Setters = { new Setter(Visual.IsVisibleProperty, true) }
},
new KeyFrame
{
Cue = new Cue(Math.Max(0d, visibleCue - 0.0001d)),
Setters = { new Setter(Visual.OpacityProperty, 1d) }
Setters = { new Setter(Visual.IsVisibleProperty, true) }
},
new KeyFrame
{
Cue = new Cue(visibleCue),
Setters = { new Setter(Visual.OpacityProperty, 0d) }
Setters = { new Setter(Visual.IsVisibleProperty, false) }
},
new KeyFrame
{
Cue = new Cue(1d),
Setters = { new Setter(Visual.OpacityProperty, 0d) }
Setters = { new Setter(Visual.IsVisibleProperty, false) }
}
}
};
var opacityCts = new CancellationTokenSource();
AnimationTokens.Add(opacityCts);
_ = opacityAnimation.RunAsync(border, opacityCts.Token);
var visibleCts = new CancellationTokenSource();
AnimationTokens.Add(visibleCts);
_ = visibleAnimation.RunAsync(border, visibleCts.Token);
}
}
}
@@ -166,7 +166,7 @@ public class LoadingCircle : LoadingBase
Child = ellipse,
RenderTransformOrigin = RelativePoint.Center,
RenderTransform = rotate,
Opacity = needHidden ? 0d : 1d
IsVisible = !needHidden
};
border.Bind(WidthProperty, new Binding(nameof(Width)) { Source = this });
border.Bind(HeightProperty, new Binding(nameof(Height)) { Source = this });
@@ -0,0 +1,193 @@
using System;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace HandyControl.Controls;
public class GotoTop : Button
{
public static readonly StyledProperty<Control?> TargetProperty =
AvaloniaProperty.Register<GotoTop, Control?>(nameof(Target));
public static readonly StyledProperty<bool> AnimatedProperty =
AvaloniaProperty.Register<GotoTop, bool>(nameof(Animated), true);
public static readonly StyledProperty<double> AnimationTimeProperty =
AvaloniaProperty.Register<GotoTop, double>(nameof(AnimationTime), 200d);
public static readonly StyledProperty<double> HidingHeightProperty =
AvaloniaProperty.Register<GotoTop, double>(nameof(HidingHeight));
public static readonly StyledProperty<bool> AutoHidingProperty =
AvaloniaProperty.Register<GotoTop, bool>(nameof(AutoHiding), true);
private ScrollViewer? _scrollViewer;
private DispatcherTimer? _animationTimer;
private DateTime _animationStartTime;
private double _animationStartOffset;
static GotoTop()
{
TargetProperty.Changed.AddClassHandler<GotoTop>((gotoTop, e) => gotoTop.CreateGotoAction(e.GetNewValue<Control?>()));
AutoHidingProperty.Changed.AddClassHandler<GotoTop>((gotoTop, _) => gotoTop.UpdateVisibility());
HidingHeightProperty.Changed.AddClassHandler<GotoTop>((gotoTop, _) => gotoTop.UpdateVisibility());
}
public GotoTop()
{
Loaded += (_, _) => CreateGotoAction(Target);
}
public Control? Target
{
get => GetValue(TargetProperty);
set => SetValue(TargetProperty, value);
}
public bool Animated
{
get => GetValue(AnimatedProperty);
set => SetValue(AnimatedProperty, value);
}
public double AnimationTime
{
get => GetValue(AnimationTimeProperty);
set => SetValue(AnimationTimeProperty, value);
}
public double HidingHeight
{
get => GetValue(HidingHeightProperty);
set => SetValue(HidingHeightProperty, value);
}
public bool AutoHiding
{
get => GetValue(AutoHidingProperty);
set => SetValue(AutoHidingProperty, value);
}
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
if (_scrollViewer != null)
{
_scrollViewer.ScrollChanged -= ScrollViewerOnScrollChanged;
}
if (_animationTimer != null)
{
_animationTimer.Stop();
}
}
public virtual void CreateGotoAction(Control? obj)
{
if (_scrollViewer != null)
{
_scrollViewer.ScrollChanged -= ScrollViewerOnScrollChanged;
}
_scrollViewer = null;
var target = obj ?? this;
if (target is ScrollViewer directScrollViewer)
{
_scrollViewer = directScrollViewer;
}
else
{
_scrollViewer = target.GetVisualDescendants().OfType<ScrollViewer>().FirstOrDefault();
}
if (_scrollViewer != null)
{
_scrollViewer.ScrollChanged += ScrollViewerOnScrollChanged;
}
UpdateVisibility();
}
private void ScrollViewerOnScrollChanged(object? sender, ScrollChangedEventArgs e)
{
UpdateVisibility();
}
private void UpdateVisibility()
{
if (!AutoHiding)
{
IsVisible = true;
return;
}
IsVisible = (_scrollViewer?.Offset.Y ?? 0d) >= HidingHeight;
}
protected override void OnClick()
{
base.OnClick();
if (_scrollViewer == null)
{
return;
}
if (!Animated || AnimationTime <= 0)
{
_scrollViewer.Offset = new Vector(_scrollViewer.Offset.X, 0);
return;
}
StartAnimatedScroll();
}
private void StartAnimatedScroll()
{
if (_scrollViewer == null)
{
return;
}
_animationStartOffset = _scrollViewer.Offset.Y;
if (_animationStartOffset <= 0)
{
return;
}
_animationStartTime = DateTime.Now;
_animationTimer ??= new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(16) };
_animationTimer.Tick -= AnimationTimerOnTick;
_animationTimer.Tick += AnimationTimerOnTick;
_animationTimer.Start();
}
private void AnimationTimerOnTick(object? sender, EventArgs e)
{
if (_scrollViewer == null)
{
_animationTimer?.Stop();
return;
}
var total = Math.Max(AnimationTime, 1d);
var elapsed = (DateTime.Now - _animationStartTime).TotalMilliseconds;
var progress = Math.Clamp(elapsed / total, 0d, 1d);
var current = _animationStartOffset * (1d - progress);
_scrollViewer.Offset = new Vector(_scrollViewer.Offset.X, current);
if (progress >= 1d)
{
_animationTimer?.Stop();
_scrollViewer.Offset = new Vector(_scrollViewer.Offset.X, 0d);
}
}
}
@@ -0,0 +1,389 @@
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.Styling;
using HandyControl.Data;
namespace HandyControl.Controls;
[TemplatePart(Name = ElementButtonLeft, Type = typeof(Button))]
[TemplatePart(Name = ElementButtonRight, Type = typeof(Button))]
[TemplatePart(Name = ElementButtonFirst, Type = typeof(RadioButton))]
[TemplatePart(Name = ElementMoreLeft, Type = typeof(Control))]
[TemplatePart(Name = ElementPanelMain, Type = typeof(Panel))]
[TemplatePart(Name = ElementMoreRight, Type = typeof(Control))]
[TemplatePart(Name = ElementButtonLast, Type = typeof(RadioButton))]
[TemplatePart(Name = ElementJump, Type = typeof(NumericUpDown))]
[TemplatePart(Name = ElementButtonJump, Type = typeof(Button))]
public class Pagination : TemplatedControl
{
private const string ElementButtonLeft = "PART_ButtonLeft";
private const string ElementButtonRight = "PART_ButtonRight";
private const string ElementButtonFirst = "PART_ButtonFirst";
private const string ElementMoreLeft = "PART_MoreLeft";
private const string ElementPanelMain = "PART_PanelMain";
private const string ElementMoreRight = "PART_MoreRight";
private const string ElementButtonLast = "PART_ButtonLast";
private const string ElementJump = "PART_Jump";
private const string ElementButtonJump = "PART_ButtonJump";
public static readonly RoutedEvent<FunctionEventArgs<int>> PageUpdatedEvent =
RoutedEvent.Register<Pagination, FunctionEventArgs<int>>(nameof(PageUpdated), RoutingStrategies.Bubble);
public static readonly StyledProperty<int> MaxPageCountProperty =
AvaloniaProperty.Register<Pagination, int>(nameof(MaxPageCount), 1);
public static readonly StyledProperty<int> DataCountPerPageProperty =
AvaloniaProperty.Register<Pagination, int>(nameof(DataCountPerPage), 20);
public static readonly StyledProperty<int> PageIndexProperty =
AvaloniaProperty.Register<Pagination, int>(nameof(PageIndex), 1);
public static readonly StyledProperty<int> MaxPageIntervalProperty =
AvaloniaProperty.Register<Pagination, int>(nameof(MaxPageInterval), 3);
public static readonly StyledProperty<bool> IsJumpEnabledProperty =
AvaloniaProperty.Register<Pagination, bool>(nameof(IsJumpEnabled));
public static readonly StyledProperty<bool> AutoHidingProperty =
AvaloniaProperty.Register<Pagination, bool>(nameof(AutoHiding), true);
public static readonly StyledProperty<ControlTheme?> PaginationButtonThemeProperty =
AvaloniaProperty.Register<Pagination, ControlTheme?>(nameof(PaginationButtonTheme));
private readonly string _groupName = Guid.NewGuid().ToString("N");
private Button? _buttonLeft;
private Button? _buttonRight;
private RadioButton? _buttonFirst;
private Control? _moreLeft;
private Panel? _panelMain;
private Control? _moreRight;
private RadioButton? _buttonLast;
private NumericUpDown? _jumpNumericUpDown;
private Button? _buttonJump;
private bool _appliedTemplate;
private bool _isUpdating;
static Pagination()
{
MaxPageCountProperty.Changed.AddClassHandler<Pagination>((pagination, e) => pagination.OnMaxPageCountChanged(e));
PageIndexProperty.Changed.AddClassHandler<Pagination>((pagination, e) => pagination.OnPageIndexChanged(e));
MaxPageIntervalProperty.Changed.AddClassHandler<Pagination>((pagination, _) => pagination.Update());
DataCountPerPageProperty.Changed.AddClassHandler<Pagination>((pagination, _) => pagination.Update());
AutoHidingProperty.Changed.AddClassHandler<Pagination>((pagination, _) => pagination.OnAutoHidingChanged());
}
public event EventHandler<FunctionEventArgs<int>> PageUpdated
{
add => AddHandler(PageUpdatedEvent, value);
remove => RemoveHandler(PageUpdatedEvent, value);
}
public int MaxPageCount
{
get => GetValue(MaxPageCountProperty);
set => SetValue(MaxPageCountProperty, value);
}
public int DataCountPerPage
{
get => GetValue(DataCountPerPageProperty);
set => SetValue(DataCountPerPageProperty, value);
}
public int PageIndex
{
get => GetValue(PageIndexProperty);
set => SetValue(PageIndexProperty, value);
}
public int MaxPageInterval
{
get => GetValue(MaxPageIntervalProperty);
set => SetValue(MaxPageIntervalProperty, value);
}
public bool IsJumpEnabled
{
get => GetValue(IsJumpEnabledProperty);
set => SetValue(IsJumpEnabledProperty, value);
}
public bool AutoHiding
{
get => GetValue(AutoHidingProperty);
set => SetValue(AutoHidingProperty, value);
}
public ControlTheme? PaginationButtonTheme
{
get => GetValue(PaginationButtonThemeProperty);
set => SetValue(PaginationButtonThemeProperty, value);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
_appliedTemplate = false;
if (_buttonLeft != null)
{
_buttonLeft.Click -= ButtonPrevOnClick;
}
if (_buttonRight != null)
{
_buttonRight.Click -= ButtonNextOnClick;
}
if (_buttonFirst != null)
{
_buttonFirst.Checked -= ToggleButtonOnChecked;
}
if (_buttonLast != null)
{
_buttonLast.Checked -= ToggleButtonOnChecked;
}
if (_buttonJump != null)
{
_buttonJump.Click -= ButtonJumpOnClick;
}
base.OnApplyTemplate(e);
_buttonLeft = e.NameScope.Find<Button>(ElementButtonLeft);
_buttonRight = e.NameScope.Find<Button>(ElementButtonRight);
_buttonFirst = e.NameScope.Find<RadioButton>(ElementButtonFirst);
_moreLeft = e.NameScope.Find<Control>(ElementMoreLeft);
_panelMain = e.NameScope.Find<Panel>(ElementPanelMain);
_moreRight = e.NameScope.Find<Control>(ElementMoreRight);
_buttonLast = e.NameScope.Find<RadioButton>(ElementButtonLast);
_jumpNumericUpDown = e.NameScope.Find<NumericUpDown>(ElementJump);
_buttonJump = e.NameScope.Find<Button>(ElementButtonJump);
if (_buttonLeft == null || _buttonRight == null || _buttonFirst == null ||
_moreLeft == null || _panelMain == null || _moreRight == null || _buttonLast == null)
{
return;
}
_buttonLeft.Click += ButtonPrevOnClick;
_buttonRight.Click += ButtonNextOnClick;
_buttonFirst.Checked += ToggleButtonOnChecked;
_buttonLast.Checked += ToggleButtonOnChecked;
if (_buttonJump != null)
{
_buttonJump.Click += ButtonJumpOnClick;
}
_buttonFirst.Content = "1";
_buttonFirst.GroupName = _groupName;
_buttonLast.GroupName = _groupName;
_appliedTemplate = true;
OnAutoHidingChanged();
Update();
}
private void OnMaxPageCountChanged(AvaloniaPropertyChangedEventArgs e)
{
var newValue = Math.Max(e.GetNewValue<int>(), 1);
if (newValue != MaxPageCount)
{
SetCurrentValue(MaxPageCountProperty, newValue);
return;
}
if (PageIndex > newValue)
{
SetCurrentValue(PageIndexProperty, newValue);
}
OnAutoHidingChanged();
Update();
}
private void OnPageIndexChanged(AvaloniaPropertyChangedEventArgs e)
{
var newValue = e.GetNewValue<int>();
var clamped = Math.Clamp(newValue, 1, Math.Max(MaxPageCount, 1));
if (clamped != newValue)
{
SetCurrentValue(PageIndexProperty, clamped);
return;
}
if (_isUpdating)
{
return;
}
Update();
RaiseEvent(new FunctionEventArgs<int>(PageUpdatedEvent, this) { Info = clamped });
}
private void OnAutoHidingChanged()
{
IsVisible = !AutoHiding || MaxPageCount > 1;
}
private void ButtonPrevOnClick(object? sender, RoutedEventArgs e)
{
if (PageIndex > 1)
{
PageIndex--;
}
}
private void ButtonNextOnClick(object? sender, RoutedEventArgs e)
{
if (PageIndex < MaxPageCount)
{
PageIndex++;
}
}
private void ButtonJumpOnClick(object? sender, RoutedEventArgs e)
{
if (_jumpNumericUpDown?.Value is null)
{
return;
}
PageIndex = (int)Math.Round(_jumpNumericUpDown.Value.Value);
}
private void ToggleButtonOnChecked(object? sender, RoutedEventArgs e)
{
if (_isUpdating)
{
return;
}
if (e.Source is not RadioButton button || button.IsChecked != true)
{
return;
}
if (int.TryParse(button.Content?.ToString(), out var page))
{
PageIndex = page;
}
}
private RadioButton CreateButton(int page)
{
var button = new RadioButton
{
Theme = PaginationButtonTheme,
Content = page.ToString(),
GroupName = _groupName,
Margin = new Thickness(-1, 0, 0, 0)
};
button.Checked += ToggleButtonOnChecked;
return button;
}
private void Update()
{
if (!_appliedTemplate || _buttonLeft == null || _buttonRight == null || _buttonFirst == null ||
_buttonLast == null || _panelMain == null || _moreLeft == null || _moreRight == null)
{
return;
}
_isUpdating = true;
_buttonLeft.IsEnabled = PageIndex > 1;
_buttonRight.IsEnabled = PageIndex < MaxPageCount;
if (_jumpNumericUpDown != null)
{
_jumpNumericUpDown.Minimum = 1;
_jumpNumericUpDown.Maximum = MaxPageCount;
_jumpNumericUpDown.Value = PageIndex;
}
if (MaxPageInterval <= 0)
{
_buttonFirst.IsVisible = false;
_buttonLast.IsVisible = false;
_moreLeft.IsVisible = false;
_moreRight.IsVisible = false;
_panelMain.Children.Clear();
var selected = CreateButton(PageIndex);
selected.IsChecked = true;
_panelMain.Children.Add(selected);
_isUpdating = false;
return;
}
_buttonFirst.IsVisible = true;
_buttonLast.IsVisible = MaxPageCount > 1;
_buttonLast.Content = MaxPageCount.ToString();
var right = MaxPageCount - PageIndex;
var left = PageIndex - 1;
_moreRight.IsVisible = right > MaxPageInterval;
_moreLeft.IsVisible = left > MaxPageInterval;
// 先把所有按钮加到面板,最后才设 IsChecked,
// 确保 RadioButton 组在同级视觉树中正确互斥。
_panelMain.Children.Clear();
RadioButton? selectedButton = null;
if (PageIndex > 1 && PageIndex < MaxPageCount)
{
selectedButton = CreateButton(PageIndex);
_panelMain.Children.Add(selectedButton);
}
else if (PageIndex == 1)
{
_buttonFirst.IsChecked = true;
}
else
{
_buttonLast.IsChecked = true;
}
var sub = PageIndex;
for (var i = 0; i < MaxPageInterval - 1; i++)
{
sub--;
if (sub <= 1)
{
break;
}
_panelMain.Children.Insert(0, CreateButton(sub));
}
var add = PageIndex;
for (var i = 0; i < MaxPageInterval - 1; i++)
{
add++;
if (add >= MaxPageCount)
{
break;
}
_panelMain.Children.Add(CreateButton(add));
}
// 所有按钮就位后再勾选,确保 RadioButton 组正确
if (selectedButton != null)
{
selectedButton.IsChecked = true;
}
_isUpdating = false;
}
}
@@ -0,0 +1,30 @@
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:ClassModifier="internal"
xmlns:hc="clr-namespace:HandyControl.Controls">
<ControlTheme x:Key="DialogBaseStyle"
TargetType="hc:Dialog">
<Setter Property="Focusable" Value="False" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="MaskBrush" Value="{DynamicResource DarkOpacityBrush}" />
<Setter Property="Template">
<ControlTemplate TargetType="hc:Dialog">
<Border Name="PART_BackElement"
Background="{TemplateBinding MaskBrush}">
<ContentPresenter Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
</ControlTemplate>
</Setter>
</ControlTheme>
<ControlTheme x:Key="{x:Type hc:Dialog}"
BasedOn="{StaticResource DialogBaseStyle}"
TargetType="hc:Dialog" />
</ResourceDictionary>
@@ -0,0 +1,45 @@
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:ClassModifier="internal"
xmlns:hc="clr-namespace:HandyControl.Controls">
<ControlTheme x:Key="GotoTopBaseStyle"
BasedOn="{StaticResource ButtonBaseStyle}"
TargetType="hc:GotoTop">
<Setter Property="Width"
Value="50" />
<Setter Property="Height"
Value="50" />
<Setter Property="hc:BorderElement.CornerRadius"
Value="25" />
<Setter Property="CornerRadius"
Value="{Binding $self.(hc:BorderElement.CornerRadius)}" />
<Setter Property="hc:IconElement.Geometry"
Value="{StaticResource UpGeometry}" />
<Setter Property="hc:IconElement.Width"
Value="14" />
<Setter Property="hc:IconElement.Height"
Value="14" />
<Setter Property="Foreground"
Value="{DynamicResource PrimaryTextBrush}" />
<Setter Property="Padding"
Value="16" />
<Setter Property="BorderThickness"
Value="1" />
<Style Selector="^:pointerover">
<Setter Property="Background"
Value="{DynamicResource SecondaryRegionBrush}" />
</Style>
<Style Selector="^:pressed">
<Setter Property="Background"
Value="{DynamicResource BorderBrush}" />
</Style>
</ControlTheme>
<ControlTheme x:Key="{x:Type hc:GotoTop}"
BasedOn="{StaticResource GotoTopBaseStyle}"
TargetType="hc:GotoTop" />
</ResourceDictionary>
@@ -0,0 +1,61 @@
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:ClassModifier="internal"
xmlns:hc="clr-namespace:HandyControl.Controls">
<ControlTheme x:Key="{x:Type hc:ImageSelector}"
TargetType="hc:ImageSelector">
<Setter Property="Stretch" Value="UniformToFill" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="StrokeThickness" Value="1" />
<Setter Property="Background" Value="{DynamicResource RegionBrush}" />
<Setter Property="BorderBrush" Value="{DynamicResource BorderBrush}" />
<Setter Property="StrokeDashArray" Value="2,2" />
<Setter Property="hc:BorderElement.CornerRadius"
Value="{StaticResource DefaultCornerRadius}" />
<Setter Property="Template">
<ControlTemplate>
<Border Background="{TemplateBinding Background}"
CornerRadius="{Binding $self.(hc:BorderElement.CornerRadius)}">
<hc:DashedBorder BorderDashArray="{TemplateBinding StrokeDashArray}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
BorderDashThickness="{TemplateBinding StrokeThickness}"
Background="{TemplateBinding PreviewBrush}"
CornerRadius="{Binding $self.(hc:BorderElement.CornerRadius)}"
ClipToBounds="True">
<!-- Add / Remove icon -->
<Border Width="30"
Height="30"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="{TemplateBinding Background}"
CornerRadius="15"
BorderThickness="0">
<Panel>
<Path IsVisible="{Binding HasValue, RelativeSource={RelativeSource TemplatedParent}, Converter={x:Static BoolConverters.Not}}"
Data="{StaticResource AddGeometry}"
Width="16"
Height="16"
Fill="{DynamicResource PrimaryBrush}" />
<Path IsVisible="{Binding HasValue, RelativeSource={RelativeSource TemplatedParent}}"
Data="{StaticResource RemoveGeometry}"
Width="12"
Height="12"
Fill="{DynamicResource PrimaryBrush}" />
</Panel>
</Border>
</hc:DashedBorder>
</Border>
</ControlTemplate>
</Setter>
<Style Selector="^:pointerover">
<Setter Property="Background"
Value="{DynamicResource SecondaryRegionBrush}" />
<Setter Property="BorderBrush"
Value="{DynamicResource PrimaryBrush}" />
</Style>
</ControlTheme>
</ResourceDictionary>
@@ -34,6 +34,7 @@
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Button.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/SplitButton.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/DropDownButton.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/ProgressButton.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/HyperlinkButton.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/RepeatButton.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/ToggleButton.axaml" />
@@ -49,15 +50,19 @@
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Label.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Slider.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Rate.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Pagination.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Expander.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/ProgressBar.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Loading.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Calendar.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/CalendarDatePicker.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/DatePicker.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Dialog.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Clock.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/TimePicker.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/TextBox.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/SearchBar.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/PinBox.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/AutoCompleteBox.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/ButtonSpinner.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/NumericUpDown.axaml" />
@@ -72,7 +77,9 @@
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Gravatar.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Tag.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Badge.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/GotoTop.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/Shield.axaml" />
<MergeResourceInclude Source="avares://HandyControl/Themes/Styles/ImageSelector.axaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Styles.Resources>
@@ -0,0 +1,105 @@
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:ClassModifier="internal"
xmlns:hc="clr-namespace:HandyControl.Controls">
<ControlTheme x:Key="PaginationButtonTheme"
BasedOn="{StaticResource RadioGroupItemBaseStyle}"
TargetType="RadioButton">
<Setter Property="MinWidth"
Value="30" />
<Setter Property="Padding"
Value="10,0" />
</ControlTheme>
<ControlTheme x:Key="{x:Type hc:Pagination}"
TargetType="hc:Pagination">
<Setter Property="hc:VisualElement.HighlightBorderBrush"
Value="{DynamicResource TitleBrush}" />
<Setter Property="hc:VisualElement.HighlightBackground"
Value="{DynamicResource TitleBrush}" />
<Setter Property="hc:VisualElement.HighlightForeground"
Value="{DynamicResource TextIconBrush}" />
<Setter Property="hc:BorderElement.CornerRadius"
Value="{StaticResource DefaultCornerRadius}" />
<Setter Property="PaginationButtonTheme"
Value="{StaticResource PaginationButtonTheme}" />
<Setter Property="Focusable"
Value="False" />
<Setter Property="Background"
Value="{DynamicResource RegionBrush}" />
<Setter Property="BorderBrush"
Value="{DynamicResource BorderBrush}" />
<Setter Property="Template">
<ControlTemplate>
<StackPanel Orientation="Horizontal"
VerticalAlignment="Top">
<Button x:Name="PART_ButtonLeft"
MinWidth="30"
Padding="10,8"
Theme="{StaticResource ButtonDefault}"
hc:IconElement.Geometry="{StaticResource LeftGeometry}"
hc:BorderElement.CornerRadius="{Binding $self.(hc:BorderElement.CornerRadius), Converter={StaticResource CornerRadiusSplitConverter}, ConverterParameter='1,0,0,1'}" />
<StackPanel ZIndex="999"
HorizontalAlignment="Center"
Orientation="Horizontal">
<RadioButton x:Name="PART_ButtonFirst"
Theme="{TemplateBinding PaginationButtonTheme}"
IsChecked="True" />
<Border x:Name="PART_MoreLeft"
Margin="-1,0,0,0"
BorderThickness="1"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{DynamicResource SecondaryRegionBrush}"
Padding="10,0">
<TextBlock FontWeight="Bold"
Foreground="{DynamicResource SecondaryTextBrush}"
Text="..."
VerticalAlignment="Center" />
</Border>
<StackPanel x:Name="PART_PanelMain"
Orientation="Horizontal" />
<Border x:Name="PART_MoreRight"
Margin="-1,0,0,0"
BorderThickness="1"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{DynamicResource SecondaryRegionBrush}"
Padding="10,0">
<TextBlock FontWeight="Bold"
Foreground="{DynamicResource SecondaryTextBrush}"
Text="..."
VerticalAlignment="Center" />
</Border>
<RadioButton x:Name="PART_ButtonLast"
Margin="-1,0,0,0"
Theme="{TemplateBinding PaginationButtonTheme}" />
</StackPanel>
<Button x:Name="PART_ButtonRight"
MinWidth="30"
Padding="10,8"
Margin="-1,0,0,0"
Theme="{StaticResource ButtonDefault}"
hc:IconElement.Geometry="{StaticResource RightGeometry}"
hc:BorderElement.CornerRadius="{Binding $self.(hc:BorderElement.CornerRadius), Converter={StaticResource CornerRadiusSplitConverter}, ConverterParameter='0,1,1,0'}" />
<NumericUpDown x:Name="PART_Jump"
IsEnabled="{TemplateBinding IsJumpEnabled}"
IsVisible="{TemplateBinding IsJumpEnabled}"
Margin="6,0,0,0"
Minimum="1"
Maximum="{TemplateBinding MaxPageCount}" />
<Button x:Name="PART_ButtonJump"
IsEnabled="{TemplateBinding IsJumpEnabled}"
IsVisible="{TemplateBinding IsJumpEnabled}"
Margin="6,0,0,0"
Content="Jump"
Theme="{StaticResource ButtonDefault}" />
</StackPanel>
</ControlTemplate>
</Setter>
</ControlTheme>
</ResourceDictionary>
@@ -0,0 +1,25 @@
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:ClassModifier="internal"
xmlns:hc="clr-namespace:HandyControl.Controls">
<ControlTheme x:Key="{x:Type hc:PinBox}"
TargetType="hc:PinBox">
<Setter Property="Focusable"
Value="False" />
<Setter Property="ItemMargin"
Value="4,0" />
<Setter Property="ItemWidth"
Value="{DynamicResource DefaultControlHeight}" />
<Setter Property="ItemHeight"
Value="{DynamicResource DefaultControlHeight}" />
<Setter Property="Template">
<ControlTemplate>
<UniformGrid x:Name="PART_Panel"
Columns="{TemplateBinding Length}"
Rows="1" />
</ControlTemplate>
</Setter>
</ControlTheme>
</ResourceDictionary>
@@ -0,0 +1,158 @@
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:ClassModifier="internal"
xmlns:hc="clr-namespace:HandyControl.Controls">
<ControlTheme x:Key="ProgressBarFlat4ProgressButton"
TargetType="ProgressBar">
<Setter Property="Background"
Value="Transparent" />
<Setter Property="hc:BorderElement.CornerRadius"
Value="{StaticResource DefaultCornerRadius}" />
<Setter Property="Foreground"
Value="{DynamicResource DarkMaskBrush}" />
<Setter Property="ShowProgressText"
Value="False" />
<Setter Property="Template">
<ControlTemplate>
<Border x:Name="PART_Track">
<Border x:Name="PART_Indicator"
HorizontalAlignment="Left">
<Border Background="{TemplateBinding Foreground}"
CornerRadius="{Binding Path=(hc:BorderElement.CornerRadius), RelativeSource={RelativeSource TemplatedParent}}" />
</Border>
</Border>
</ControlTemplate>
</Setter>
</ControlTheme>
<ControlTheme x:Key="ProgressButtonBaseStyle"
BasedOn="{StaticResource ToggleButtonBaseStyle}"
TargetType="hc:ProgressButton">
<Setter Property="Background"
Value="{DynamicResource RegionBrush}" />
<Setter Property="ProgressTheme"
Value="{StaticResource ProgressBarFlat4ProgressButton}" />
<Setter Property="Template">
<ControlTemplate>
<Border x:Name="Chrome"
CornerRadius="{TemplateBinding CornerRadius}"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}">
<Panel>
<ProgressBar x:Name="ProgressBar"
Maximum="100"
Value="{TemplateBinding Progress}"
Theme="{TemplateBinding ProgressTheme}"
IsVisible="False" />
<ContentPresenter x:Name="UnCheckedElement"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
RecognizesAccessKey="True"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}" />
<ContentPresenter x:Name="CheckedElement"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
RecognizesAccessKey="True"
Content="{TemplateBinding hc:StatusSwitchElement.CheckedElement}"
ContentTemplate="{TemplateBinding ContentTemplate}"
IsVisible="False" />
</Panel>
</Border>
</ControlTemplate>
</Setter>
<Style Selector="^:pointerover">
<Setter Property="Opacity"
Value="0.9" />
</Style>
<Style Selector="^:pressed">
<Setter Property="Opacity"
Value="0.6" />
</Style>
<Style Selector="^:checked /template/ ProgressBar#ProgressBar">
<Setter Property="IsVisible"
Value="True" />
</Style>
<Style Selector="^:checked /template/ ContentPresenter#CheckedElement">
<Setter Property="IsVisible"
Value="True" />
</Style>
<Style Selector="^[(hc|StatusSwitchElement.HideUncheckedElement)=True]:checked /template/ ContentPresenter#UnCheckedElement">
<Setter Property="IsVisible"
Value="False" />
</Style>
<Style Selector="^:disabled">
<Setter Property="Opacity"
Value="0.4" />
</Style>
</ControlTheme>
<ControlTheme x:Key="ProgressButtonDefault"
BasedOn="{StaticResource ProgressButtonBaseStyle}"
TargetType="hc:ProgressButton">
<Setter Property="Foreground"
Value="{DynamicResource PrimaryTextBrush}" />
<Setter Property="BorderThickness"
Value="1" />
<Style Selector="^:pointerover">
<Setter Property="Background"
Value="{DynamicResource SecondaryRegionBrush}" />
</Style>
<Style Selector="^:pressed">
<Setter Property="Background"
Value="{DynamicResource BorderBrush}" />
</Style>
</ControlTheme>
<ControlTheme x:Key="{x:Type hc:ProgressButton}"
BasedOn="{StaticResource ProgressButtonDefault}"
TargetType="hc:ProgressButton" />
<ControlTheme x:Key="ProgressButtonPrimary"
BasedOn="{StaticResource ProgressButtonBaseStyle}"
TargetType="hc:ProgressButton">
<Setter Property="Background"
Value="{DynamicResource PrimaryBrush}" />
</ControlTheme>
<ControlTheme x:Key="ProgressButtonSuccess"
BasedOn="{StaticResource ProgressButtonBaseStyle}"
TargetType="hc:ProgressButton">
<Setter Property="Background"
Value="{DynamicResource SuccessBrush}" />
</ControlTheme>
<ControlTheme x:Key="ProgressButtonInfo"
BasedOn="{StaticResource ProgressButtonBaseStyle}"
TargetType="hc:ProgressButton">
<Setter Property="Background"
Value="{DynamicResource InfoBrush}" />
</ControlTheme>
<ControlTheme x:Key="ProgressButtonWarning"
BasedOn="{StaticResource ProgressButtonBaseStyle}"
TargetType="hc:ProgressButton">
<Setter Property="Background"
Value="{DynamicResource WarningBrush}" />
</ControlTheme>
<ControlTheme x:Key="ProgressButtonDanger"
BasedOn="{StaticResource ProgressButtonBaseStyle}"
TargetType="hc:ProgressButton">
<Setter Property="Background"
Value="{DynamicResource DangerBrush}" />
</ControlTheme>
</ResourceDictionary>
@@ -0,0 +1,294 @@
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:ClassModifier="internal"
xmlns:hc="clr-namespace:HandyControl.Controls"
xmlns:sys="using:System">
<ControlTheme x:Key="SearchBarBaseStyle"
BasedOn="{StaticResource TextBoxBaseStyle}"
TargetType="hc:SearchBar">
<Setter Property="Template">
<ControlTemplate>
<DataValidationErrors>
<Panel>
<Border x:Name="border"
CornerRadius="{TemplateBinding CornerRadius}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}" />
<Grid ColumnDefinitions="*,Auto">
<TextBlock Grid.Column="0"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Margin="{TemplateBinding Padding}"
IsVisible="{TemplateBinding Text, Converter={x:Static StringConverters.IsNullOrEmpty}}"
HorizontalAlignment="Stretch"
Theme="{StaticResource TextBlockDefaultThiLight}"
Text="{TemplateBinding Watermark}" />
<ScrollViewer Grid.Column="0"
Name="PART_ScrollViewer"
AllowAutoHide="{TemplateBinding (ScrollViewer.AllowAutoHide)}"
BringIntoViewOnFocusChange="{TemplateBinding (ScrollViewer.BringIntoViewOnFocusChange)}"
HorizontalScrollBarVisibility="Hidden"
IsScrollChainingEnabled="{TemplateBinding (ScrollViewer.IsScrollChainingEnabled)}"
VerticalScrollBarVisibility="Hidden">
<TextPresenter Name="PART_TextPresenter"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
CaretBlinkInterval="{TemplateBinding CaretBlinkInterval}"
CaretBrush="{TemplateBinding CaretBrush}"
CaretIndex="{TemplateBinding CaretIndex}"
LineHeight="{TemplateBinding LineHeight}"
LetterSpacing="{TemplateBinding LetterSpacing}"
PasswordChar="{TemplateBinding PasswordChar}"
RevealPassword="{TemplateBinding RevealPassword}"
SelectionBrush="{TemplateBinding SelectionBrush}"
SelectionEnd="{TemplateBinding SelectionEnd}"
SelectionForegroundBrush="{TemplateBinding SelectionForegroundBrush}"
SelectionStart="{TemplateBinding SelectionStart}"
Text="{TemplateBinding Text, Mode=TwoWay}"
TextAlignment="{TemplateBinding TextAlignment}"
TextWrapping="{TemplateBinding TextWrapping}" />
</ScrollViewer>
<Button Grid.Column="1"
x:Name="PART_SearchButton"
HorizontalContentAlignment="Left"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Focusable="False"
Theme="{StaticResource ButtonIcon}"
hc:IconElement.Width="14"
Padding="{Binding Padding, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource ThicknessSplitConverter}, ConverterParameter='0,0,1,0'}"
hc:IconElement.Geometry="{StaticResource SearchGeometry}"
Foreground="{Binding BorderBrush, ElementName=border}" />
</Grid>
</Panel>
</DataValidationErrors>
</ControlTemplate>
</Setter>
<Style Selector="^:disabled">
<Setter Property="Opacity"
Value="0.4" />
</Style>
<Style Selector="^:pointerover /template/ Border#border">
<Setter Property="BorderBrush"
Value="{DynamicResource SecondaryBorderBrush}" />
</Style>
<Style Selector="^:focus">
<Style Selector="^:pointerover /template/ Border#border">
<Setter Property="BorderBrush"
Value="{DynamicResource PrimaryBrush}" />
</Style>
<Setter Property="BorderBrush"
Value="{DynamicResource PrimaryBrush}" />
</Style>
<Style Selector="^:error /template/ Border#border">
<Setter Property="BorderBrush"
Value="{DynamicResource DangerBrush}" />
</Style>
</ControlTheme>
<ControlTheme x:Key="{x:Type hc:SearchBar}"
BasedOn="{StaticResource SearchBarBaseStyle}"
TargetType="hc:SearchBar" />
<ControlTheme x:Key="SearchBar.Small"
BasedOn="{StaticResource SearchBarBaseStyle}"
TargetType="hc:SearchBar">
<Setter Property="MinHeight"
Value="20" />
<Setter Property="Padding"
Value="6,0" />
</ControlTheme>
<ControlTheme x:Key="SearchBarExtend"
BasedOn="{StaticResource SearchBarBaseStyle}"
TargetType="hc:SearchBar">
<Setter Property="hc:InfoElement.Symbol"
Value="●" />
<Setter Property="hc:InfoElement.ContentHeight"
Value="{x:Static sys:Double.NaN}" />
<Setter Property="hc:InfoElement.MinContentHeight"
Value="{StaticResource DefaultControlHeight}" />
<Setter Property="Template">
<ControlTemplate>
<HeaderedContentControl Header="{Binding $parent.(hc:TitleElement.Title)}">
<Grid ColumnDefinitions="*,Auto">
<Border x:Name="border"
Grid.ColumnSpan="2"
CornerRadius="{TemplateBinding CornerRadius}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}" />
<TextBlock Grid.Column="0"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Margin="{TemplateBinding Padding}"
IsVisible="{TemplateBinding Text, Converter={x:Static StringConverters.IsNullOrEmpty}}"
HorizontalAlignment="Stretch"
Theme="{StaticResource TextBlockDefaultThiLight}"
Text="{TemplateBinding Watermark}" />
<ScrollViewer Grid.Column="0"
Name="PART_ScrollViewer"
AllowAutoHide="{TemplateBinding (ScrollViewer.AllowAutoHide)}"
BringIntoViewOnFocusChange="{TemplateBinding (ScrollViewer.BringIntoViewOnFocusChange)}"
HorizontalScrollBarVisibility="Hidden"
IsScrollChainingEnabled="{TemplateBinding (ScrollViewer.IsScrollChainingEnabled)}"
VerticalScrollBarVisibility="Hidden">
<TextPresenter Name="PART_TextPresenter"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
CaretBlinkInterval="{TemplateBinding CaretBlinkInterval}"
CaretBrush="{TemplateBinding CaretBrush}"
CaretIndex="{TemplateBinding CaretIndex}"
LineHeight="{TemplateBinding LineHeight}"
LetterSpacing="{TemplateBinding LetterSpacing}"
PasswordChar="{TemplateBinding PasswordChar}"
RevealPassword="{TemplateBinding RevealPassword}"
SelectionBrush="{TemplateBinding SelectionBrush}"
SelectionEnd="{TemplateBinding SelectionEnd}"
SelectionForegroundBrush="{TemplateBinding SelectionForegroundBrush}"
SelectionStart="{TemplateBinding SelectionStart}"
Text="{TemplateBinding Text, Mode=TwoWay}"
TextAlignment="{TemplateBinding TextAlignment}"
TextWrapping="{TemplateBinding TextWrapping}" />
</ScrollViewer>
<Button Grid.Column="1"
x:Name="PART_SearchButton"
HorizontalContentAlignment="Left"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Focusable="False"
Theme="{StaticResource ButtonIcon}"
hc:IconElement.Width="14"
Padding="{Binding Padding, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource ThicknessSplitConverter}, ConverterParameter='0,0,1,0'}"
hc:IconElement.Geometry="{StaticResource SearchGeometry}"
Foreground="{Binding BorderBrush, ElementName=border}" />
</Grid>
</HeaderedContentControl>
</ControlTemplate>
</Setter>
</ControlTheme>
<ControlTheme x:Key="SearchBarExtend.Small"
BasedOn="{StaticResource SearchBarExtend}"
TargetType="hc:SearchBar">
<Setter Property="hc:InfoElement.MinContentHeight"
Value="20" />
<Setter Property="hc:InfoElement.ContentHeight"
Value="20" />
<Setter Property="hc:TitleElement.MarginOnTheLeft"
Value="0,3,6,0" />
<Setter Property="hc:TitleElement.MarginOnTheTop"
Value="6,0,0,1" />
<Setter Property="Padding"
Value="6,0" />
<Setter Property="MinHeight"
Value="20" />
</ControlTheme>
<ControlTheme x:Key="SearchBarPlus"
BasedOn="{StaticResource SearchBarExtend}"
TargetType="hc:SearchBar">
<Setter Property="Template">
<ControlTemplate>
<HeaderedContentControl Header="{Binding $parent.(hc:TitleElement.Title)}">
<Grid ColumnDefinitions="*,Auto,Auto">
<Border x:Name="border"
Grid.ColumnSpan="3"
CornerRadius="{TemplateBinding CornerRadius}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}" />
<TextBlock Grid.Column="0"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Margin="{TemplateBinding Padding}"
IsVisible="{TemplateBinding Text, Converter={x:Static StringConverters.IsNullOrEmpty}}"
HorizontalAlignment="Stretch"
Theme="{StaticResource TextBlockDefaultThiLight}"
Text="{TemplateBinding Watermark}" />
<ScrollViewer Grid.Column="0"
Name="PART_ScrollViewer"
AllowAutoHide="{TemplateBinding (ScrollViewer.AllowAutoHide)}"
BringIntoViewOnFocusChange="{TemplateBinding (ScrollViewer.BringIntoViewOnFocusChange)}"
HorizontalScrollBarVisibility="Hidden"
IsScrollChainingEnabled="{TemplateBinding (ScrollViewer.IsScrollChainingEnabled)}"
VerticalScrollBarVisibility="Hidden">
<TextPresenter Name="PART_TextPresenter"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
CaretBlinkInterval="{TemplateBinding CaretBlinkInterval}"
CaretBrush="{TemplateBinding CaretBrush}"
CaretIndex="{TemplateBinding CaretIndex}"
LineHeight="{TemplateBinding LineHeight}"
LetterSpacing="{TemplateBinding LetterSpacing}"
PasswordChar="{TemplateBinding PasswordChar}"
RevealPassword="{TemplateBinding RevealPassword}"
SelectionBrush="{TemplateBinding SelectionBrush}"
SelectionEnd="{TemplateBinding SelectionEnd}"
SelectionForegroundBrush="{TemplateBinding SelectionForegroundBrush}"
SelectionStart="{TemplateBinding SelectionStart}"
Text="{TemplateBinding Text, Mode=TwoWay}"
TextAlignment="{TemplateBinding TextAlignment}"
TextWrapping="{TemplateBinding TextWrapping}" />
</ScrollViewer>
<Button Grid.Column="1"
HorizontalContentAlignment="Left"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Focusable="False"
Theme="{StaticResource ButtonIcon}"
hc:IconElement.Width="14"
Padding="0,0,2,0"
hc:IconElement.Geometry="{StaticResource DeleteFillCircleGeometry}"
Foreground="{Binding BorderBrush, ElementName=border}"
Command="{Binding $parent[TextBox].Clear}">
<Button.IsVisible>
<MultiBinding Converter="{x:Static BoolConverters.And}">
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="IsPointerOver" />
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="(hc:InfoElement.ShowClearButton)" />
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="IsReadOnly"
Converter="{x:Static BoolConverters.Not}" />
</MultiBinding>
</Button.IsVisible>
</Button>
<Button Grid.Column="2"
x:Name="PART_SearchButton"
HorizontalContentAlignment="Left"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Focusable="False"
Theme="{StaticResource ButtonIcon}"
hc:IconElement.Width="14"
Padding="{Binding Padding, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource ThicknessSplitConverter}, ConverterParameter='0,0,1,0'}"
hc:IconElement.Geometry="{StaticResource SearchGeometry}"
Foreground="{Binding BorderBrush, ElementName=border}" />
</Grid>
</HeaderedContentControl>
</ControlTemplate>
</Setter>
</ControlTheme>
<ControlTheme x:Key="SearchBarPlus.Small"
BasedOn="{StaticResource SearchBarPlus}"
TargetType="hc:SearchBar">
<Setter Property="hc:InfoElement.MinContentHeight"
Value="20" />
<Setter Property="hc:InfoElement.ContentHeight"
Value="20" />
<Setter Property="hc:TitleElement.MarginOnTheLeft"
Value="0,3,6,0" />
<Setter Property="hc:TitleElement.MarginOnTheTop"
Value="6,0,0,1" />
<Setter Property="Padding"
Value="6,0" />
<Setter Property="MinHeight"
Value="20" />
</ControlTheme>
</ResourceDictionary>
@@ -895,4 +895,129 @@
<Setter Property="hc:BorderElement.CornerRadius"
Value="0,0,4,4" />
</ControlTheme>
<ControlTheme x:Key="ToggleButtonLoadingPrimary"
BasedOn="{StaticResource ToggleButtonBaseStyle}"
TargetType="ToggleButton">
<Setter Property="Background"
Value="{DynamicResource PrimaryBrush}" />
<Setter Property="Template">
<ControlTemplate>
<Border x:Name="Chrome"
CornerRadius="{TemplateBinding CornerRadius}"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}">
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
<Panel>
<ContentPresenter x:Name="UnCheckedElement"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
RecognizesAccessKey="True"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}" />
<ContentPresenter x:Name="CheckedElement"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
RecognizesAccessKey="True"
IsVisible="False"
Content="{TemplateBinding hc:StatusSwitchElement.CheckedElement}"
ContentTemplate="{TemplateBinding ContentTemplate}" />
</Panel>
<Viewbox Margin="0,4">
<hc:LoadingCircle x:Name="Loading"
Width="22"
Height="22"
Foreground="{TemplateBinding Foreground}"
DotDiameter="3"
IsRunning="{TemplateBinding IsChecked}"
IsVisible="False" />
</Viewbox>
</StackPanel>
</Border>
</ControlTemplate>
</Setter>
<Style Selector="^:pointerover">
<Setter Property="Opacity"
Value="0.9" />
</Style>
<Style Selector="^:pressed">
<Setter Property="Opacity"
Value="0.6" />
</Style>
<Style Selector="^:checked /template/ hc|LoadingCircle#Loading">
<Setter Property="IsVisible"
Value="True" />
</Style>
<Style Selector="^:checked /template/ ContentPresenter#CheckedElement">
<Setter Property="IsVisible"
Value="True" />
</Style>
<Style Selector="^[(hc|StatusSwitchElement.HideUncheckedElement)=True]:checked /template/ ContentPresenter#UnCheckedElement">
<Setter Property="IsVisible"
Value="False" />
</Style>
<Style Selector="^:disabled">
<Setter Property="Opacity"
Value="0.4" />
</Style>
</ControlTheme>
<ControlTheme x:Key="ToggleButtonLoading"
BasedOn="{StaticResource ToggleButtonLoadingPrimary}"
TargetType="ToggleButton">
<Setter Property="Background"
Value="{DynamicResource RegionBrush}" />
<Setter Property="Foreground"
Value="{DynamicResource PrimaryTextBrush}" />
<Setter Property="BorderThickness"
Value="1" />
<Style Selector="^:pointerover">
<Setter Property="Background"
Value="{DynamicResource SecondaryRegionBrush}" />
</Style>
<Style Selector="^:pressed">
<Setter Property="Background"
Value="{DynamicResource BorderBrush}" />
</Style>
</ControlTheme>
<ControlTheme x:Key="ToggleButtonLoadingSuccess"
BasedOn="{StaticResource ToggleButtonLoadingPrimary}"
TargetType="ToggleButton">
<Setter Property="Background"
Value="{DynamicResource SuccessBrush}" />
</ControlTheme>
<ControlTheme x:Key="ToggleButtonLoadingInfo"
BasedOn="{StaticResource ToggleButtonLoadingPrimary}"
TargetType="ToggleButton">
<Setter Property="Background"
Value="{DynamicResource InfoBrush}" />
</ControlTheme>
<ControlTheme x:Key="ToggleButtonLoadingWarning"
BasedOn="{StaticResource ToggleButtonLoadingPrimary}"
TargetType="ToggleButton">
<Setter Property="Background"
Value="{DynamicResource WarningBrush}" />
</ControlTheme>
<ControlTheme x:Key="ToggleButtonLoadingDanger"
BasedOn="{StaticResource ToggleButtonLoadingPrimary}"
TargetType="ToggleButton">
<Setter Property="Background"
Value="{DynamicResource DangerBrush}" />
</ControlTheme>
</ResourceDictionary>
@@ -0,0 +1,77 @@
using System;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
using HandyControl.Controls;
namespace HandyControl.Tools.Extension;
public interface IDialogResultable<T>
{
T Result { get; set; }
Action CloseAction { get; set; }
}
public static class DialogExtension
{
public static Task<TResult> GetResultAsync<TResult>(this Dialog dialog)
{
var tcs = new TaskCompletionSource<TResult>();
try
{
if (dialog.IsClosed)
{
SetResult();
}
else
{
dialog.Unloaded += OnUnloaded;
dialog.GetViewModel<IDialogResultable<TResult>>().CloseAction = dialog.Close;
}
}
catch (Exception e)
{
tcs.TrySetException(e);
}
return tcs.Task;
void OnUnloaded(object? sender, RoutedEventArgs args)
{
dialog.Unloaded -= OnUnloaded;
SetResult();
}
void SetResult()
{
try
{
tcs.TrySetResult(dialog.GetViewModel<IDialogResultable<TResult>>().Result);
}
catch (Exception e)
{
tcs.TrySetException(e);
}
}
}
public static Dialog Initialize<TViewModel>(this Dialog dialog, Action<TViewModel> configure)
{
configure?.Invoke(dialog.GetViewModel<TViewModel>());
return dialog;
}
public static TViewModel GetViewModel<TViewModel>(this Dialog dialog)
{
if (!(dialog.Content is Control frameworkElement))
throw new InvalidOperationException("The dialog is not a derived class of the FrameworkElement. ");
if (!(frameworkElement.DataContext is TViewModel viewModel))
throw new InvalidOperationException($"The view model of the dialog is not the {typeof(TViewModel)} type or its derived class. ");
return viewModel;
}
}
@@ -5,14 +5,19 @@
<TargetFrameworks>netcoreapp3.0;netcoreapp3.1;net45;net451;net452;net46;net461;net462;net47;net471;net472;net48;net481;net5.0-windows;net6.0-windows;net7.0-windows;net8.0-windows;net9.0-windows;net10.0-windows</TargetFrameworks>
<Description>Contains some simple and commonly used WPF controls</Description>
<PackageId>HandyControl</PackageId>
<Version>3.6.1.0</Version>
<AssemblyVersion>3.6.1.0</AssemblyVersion>
<FileVersion>3.6.1.0</FileVersion>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<NoWarn>0067;0649;1591;MSB3061;SYSLIB0003;SYSLIB0004;SYSLIB0032;CA2022</NoWarn>
<MSBuildWarningsAsMessages>NETSDK1138</MSBuildWarningsAsMessages>
<AssemblyOriginatorKeyFile>..\..\Shared\HandyControl_Shared\key.snk</AssemblyOriginatorKeyFile>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageTags>WPF C# Control</PackageTags>
<PackageReleaseNotes>Changes are detailed at https://github.com/HandyOrg/HandyControl/releases</PackageReleaseNotes>
<RepositoryType>git</RepositoryType>
<SatelliteResourceLanguages>zh;</SatelliteResourceLanguages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<SignAssembly>true</SignAssembly>
@@ -33,42 +38,6 @@
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.tr.resx">
<Link>Properties\Langs\Lang.tr.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.ca-ES.resx">
<Link>Properties\Langs\Lang.ca-ES.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.cs.resx">
<Link>Properties\Langs\Lang.cs.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.en.resx">
<Link>Properties\Langs\Lang.en.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.es.resx">
<Link>Properties\Langs\Lang.es.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.fa.resx">
<Link>Properties\Langs\Lang.fa.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.fr.resx">
<Link>Properties\Langs\Lang.fr.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.ja.resx">
<Link>Properties\Langs\Lang.ja.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.ko-KR.resx">
<Link>Properties\Langs\Lang.ko-KR.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.pl.resx">
<Link>Properties\Langs\Lang.pl.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.pt-BR.resx">
<Link>Properties\Langs\Lang.pt-BR.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.ru.resx">
<Link>Properties\Langs\Lang.ru.resx</Link>
</EmbeddedResource>
<EmbeddedResource Include="..\..\Shared\HandyControl_Shared\Properties\Langs\Lang.resx">
<Link>Properties\Langs\Lang.resx</Link>
<Generator>PublicResXFileCodeGenerator</Generator>