├── .gitattributes
├── .gitignore
├── AvaloniaTokenizingTextBox.Sample
├── App.axaml
├── App.axaml.cs
├── Assets
│ └── avalonia-logo.ico
├── AvaloniaTokenizingTextBox.Sample.csproj
├── Program.cs
├── ViewLocator.cs
├── ViewModels
│ ├── MainWindowViewModel.cs
│ └── ViewModelBase.cs
├── Views
│ ├── MainWindow.axaml
│ └── MainWindow.axaml.cs
└── nuget.config
├── AvaloniaTokenizingTextBox.Tests
├── AvaloniaTokenizingTextBox.Tests.csproj
└── TokenizingTextBoxTests.cs
├── AvaloniaTokenizingTextBox.sln
├── AvaloniaTokenizingTextBox
├── AvaloniaTokenizingTextBox.csproj
├── Controls
│ ├── StretchChild.cs
│ ├── TokenTextBox.cs
│ ├── TokenizingTextBox.cs
│ ├── TokenizingTextBoxItem.cs
│ └── TokenizingWrapPanel.cs
└── Styles
│ ├── Generic.xaml
│ ├── TokenizingTextBox.xaml
│ └── TokenizingTextBoxItem.xaml
├── LICENSE
└── README.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Oo]ut/
33 | [Ll]og/
34 | [Ll]ogs/
35 |
36 | # Visual Studio 2015/2017 cache/options directory
37 | .vs/
38 | # Uncomment if you have tasks that create the project's static files in wwwroot
39 | #wwwroot/
40 |
41 | # Visual Studio 2017 auto generated files
42 | Generated\ Files/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUnit
49 | *.VisualState.xml
50 | TestResult.xml
51 | nunit-*.xml
52 |
53 | # Build Results of an ATL Project
54 | [Dd]ebugPS/
55 | [Rr]eleasePS/
56 | dlldata.c
57 |
58 | # Benchmark Results
59 | BenchmarkDotNet.Artifacts/
60 |
61 | # .NET Core
62 | project.lock.json
63 | project.fragment.lock.json
64 | artifacts/
65 |
66 | # ASP.NET Scaffolding
67 | ScaffoldingReadMe.txt
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio LightSwitch build output
298 | **/*.HTMLClient/GeneratedArtifacts
299 | **/*.DesktopClient/GeneratedArtifacts
300 | **/*.DesktopClient/ModelManifest.xml
301 | **/*.Server/GeneratedArtifacts
302 | **/*.Server/ModelManifest.xml
303 | _Pvt_Extensions
304 |
305 | # Paket dependency manager
306 | .paket/paket.exe
307 | paket-files/
308 |
309 | # FAKE - F# Make
310 | .fake/
311 |
312 | # CodeRush personal settings
313 | .cr/personal
314 |
315 | # Python Tools for Visual Studio (PTVS)
316 | __pycache__/
317 | *.pyc
318 |
319 | # Cake - Uncomment if you are using it
320 | # tools/**
321 | # !tools/packages.config
322 |
323 | # Tabs Studio
324 | *.tss
325 |
326 | # Telerik's JustMock configuration file
327 | *.jmconfig
328 |
329 | # BizTalk build output
330 | *.btp.cs
331 | *.btm.cs
332 | *.odx.cs
333 | *.xsd.cs
334 |
335 | # OpenCover UI analysis results
336 | OpenCover/
337 |
338 | # Azure Stream Analytics local run output
339 | ASALocalRun/
340 |
341 | # MSBuild Binary and Structured Log
342 | *.binlog
343 |
344 | # NVidia Nsight GPU debugger configuration file
345 | *.nvuser
346 |
347 | # MFractors (Xamarin productivity tool) working folder
348 | .mfractor/
349 |
350 | # Local History for Visual Studio
351 | .localhistory/
352 |
353 | # BeatPulse healthcheck temp database
354 | healthchecksdb
355 |
356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
357 | MigrationBackup/
358 |
359 | # Ionide (cross platform F# VS Code tools) working folder
360 | .ionide/
361 |
362 | # Fody - auto-generated XML schema
363 | FodyWeavers.xsd
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/App.axaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
15 |
16 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/App.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls.ApplicationLifetimes;
3 | using Avalonia.Markup.Xaml;
4 | using AvaloniaTokenizingTextBox.Sample.ViewModels;
5 | using AvaloniaTokenizingTextBox.Sample.Views;
6 |
7 | namespace AvaloniaTokenizingTextBox.Sample;
8 |
9 | public class App : Application
10 | {
11 | public override void Initialize()
12 | {
13 | AvaloniaXamlLoader.Load(this);
14 | }
15 |
16 | public override void OnFrameworkInitializationCompleted()
17 | {
18 | if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
19 | {
20 | desktop.MainWindow = new MainWindow
21 | {
22 | DataContext = new MainWindowViewModel(),
23 | };
24 | }
25 |
26 | base.OnFrameworkInitializationCompleted();
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/Assets/avalonia-logo.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/puppetsw/AvaloniaTokenizingTextBox/a2cfa9677bc6b1425007bb6b44e1e3b560f662f6/AvaloniaTokenizingTextBox.Sample/Assets/avalonia-logo.ico
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/AvaloniaTokenizingTextBox.Sample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Exe
4 | net8.0
5 | enable
6 | True
7 | True
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/Program.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.ReactiveUI;
3 |
4 | namespace AvaloniaTokenizingTextBox.Sample;
5 |
6 | class Program
7 | {
8 | // Initialization code. Don't use any Avalonia, third-party APIs or any
9 | // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
10 | // yet and stuff might break.
11 | public static void Main(string[] args) => BuildAvaloniaApp()
12 | .StartWithClassicDesktopLifetime(args);
13 |
14 | // Avalonia configuration, don't remove; also used by visual designer.
15 | public static AppBuilder BuildAvaloniaApp()
16 | => AppBuilder.Configure()
17 | .UsePlatformDetect()
18 | .LogToTrace()
19 | .UseReactiveUI();
20 | }
21 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/ViewLocator.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Controls;
2 | using Avalonia.Controls.Templates;
3 | using AvaloniaTokenizingTextBox.Sample.ViewModels;
4 |
5 | namespace AvaloniaTokenizingTextBox.Sample;
6 |
7 | public class ViewLocator : IDataTemplate
8 | {
9 | public bool SupportsRecycling => false;
10 |
11 | public Control Build(object? data)
12 | {
13 | var name = data?.GetType().FullName?.Replace("ViewModel", "View");
14 |
15 | if (name != null)
16 | {
17 | var type = Type.GetType(name);
18 | if (type != null)
19 | {
20 | return (Control)Activator.CreateInstance(type)!;
21 | }
22 | }
23 |
24 | return new TextBlock { Text = "Not Found: " + name };
25 | }
26 |
27 | public bool Match(object? data) =>
28 | data is ViewModelBase;
29 | }
30 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/ViewModels/MainWindowViewModel.cs:
--------------------------------------------------------------------------------
1 | using ReactiveUI;
2 | using System.Collections.ObjectModel;
3 | using System.Diagnostics;
4 | using System.Windows.Input;
5 |
6 | namespace AvaloniaTokenizingTextBox.Sample.ViewModels;
7 |
8 | public class MainWindowViewModel : ViewModelBase
9 | {
10 | public ObservableCollection SelectableTokens { get; }
11 |
12 | private string? _selectedItem;
13 | public string? SelectedItem
14 | {
15 | get => _selectedItem;
16 | set => this.RaiseAndSetIfChanged(ref _selectedItem, value);
17 | }
18 |
19 | public ObservableCollection Tokens { get; }
20 |
21 | public ICommand TestCommand { get; }
22 |
23 | public MainWindowViewModel()
24 | {
25 | SelectableTokens = ["anothertest@gmail.com", "anothertest2@gmail.com", "test@gmail.com", "john.mcclane@hotmail.com"];
26 | Tokens = [];
27 | TestCommand = ReactiveCommand.Create(Test);
28 | }
29 |
30 | private void Test()
31 | {
32 | Debug.WriteLine("Selected tokens: " + string.Join(',', Tokens));
33 | //throw new System.NotImplementedException();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/ViewModels/ViewModelBase.cs:
--------------------------------------------------------------------------------
1 | using ReactiveUI;
2 |
3 | namespace AvaloniaTokenizingTextBox.Sample.ViewModels;
4 |
5 | public class ViewModelBase : ReactiveObject
6 | {
7 | }
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/Views/MainWindow.axaml:
--------------------------------------------------------------------------------
1 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/Views/MainWindow.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls;
3 | using Avalonia.Markup.Xaml;
4 |
5 | namespace AvaloniaTokenizingTextBox.Sample.Views;
6 |
7 | public partial class MainWindow : Window
8 | {
9 | public MainWindow()
10 | {
11 | InitializeComponent();
12 | #if DEBUG
13 | this.AttachDevTools();
14 | #endif
15 | }
16 |
17 | private void InitializeComponent()
18 | {
19 | AvaloniaXamlLoader.Load(this);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Sample/nuget.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Tests/AvaloniaTokenizingTextBox.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0
5 | false
6 | enable
7 | True
8 | True
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | runtime; build; native; contentfiles; analyzers; buildtransitive
18 | all
19 |
20 |
21 | runtime; build; native; contentfiles; analyzers; buildtransitive
22 | all
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.Tests/TokenizingTextBoxTests.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Data;
2 | using AvaloniaTokenizingTextBox.Controls;
3 | using Xunit;
4 | using Xunit.Abstractions;
5 |
6 | namespace AvaloniaTokenizingTextBox.Tests;
7 |
8 | public class TokenizingTextBoxTests
9 | {
10 | private readonly ITestOutputHelper _output;
11 |
12 | public TokenizingTextBoxTests(ITestOutputHelper output) => _output = output;
13 |
14 | [Fact]
15 | public void DefaultBindingMode_Should_Be_TwoWay()
16 | {
17 | Assert.Equal(BindingMode.TwoWay, TokenizingTextBox.TextProperty.GetMetadata(typeof(TokenizingTextBox)).DefaultBindingMode);
18 | }
19 |
20 | [Fact]
21 | public void SelectableTokens_Should_Filter_With_Contains_Until_Space()
22 | {
23 | var selectableTokens = new List
24 | {
25 | "test@gmail.com",
26 | "test1@gmail.com",
27 | "anothertest@gmail.com",
28 | "what@gmail.com",
29 | "test fake@gmail.com"
30 | };
31 |
32 | var filtered = selectableTokens.Where(x => x.Contains("test")).ToList();
33 |
34 | _output.WriteLine(string.Join(',', filtered));
35 | }
36 | }
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.31313.79
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaTokenizingTextBox", "AvaloniaTokenizingTextBox\AvaloniaTokenizingTextBox.csproj", "{43BAA6D7-A153-4DD7-A382-07769DADFD5B}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaTokenizingTextBox.Sample", "AvaloniaTokenizingTextBox.Sample\AvaloniaTokenizingTextBox.Sample.csproj", "{4E85425C-E17B-4867-B910-2BA71AA9D4D8}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaTokenizingTextBox.Tests", "AvaloniaTokenizingTextBox.Tests\AvaloniaTokenizingTextBox.Tests.csproj", "{DF37AC3A-535D-4AD7-83B2-B610D4825BE3}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {43BAA6D7-A153-4DD7-A382-07769DADFD5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {43BAA6D7-A153-4DD7-A382-07769DADFD5B}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {43BAA6D7-A153-4DD7-A382-07769DADFD5B}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {43BAA6D7-A153-4DD7-A382-07769DADFD5B}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {4E85425C-E17B-4867-B910-2BA71AA9D4D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {4E85425C-E17B-4867-B910-2BA71AA9D4D8}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {4E85425C-E17B-4867-B910-2BA71AA9D4D8}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {4E85425C-E17B-4867-B910-2BA71AA9D4D8}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {DF37AC3A-535D-4AD7-83B2-B610D4825BE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {DF37AC3A-535D-4AD7-83B2-B610D4825BE3}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {DF37AC3A-535D-4AD7-83B2-B610D4825BE3}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {DF37AC3A-535D-4AD7-83B2-B610D4825BE3}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {74128074-BC82-4E6A-B875-F38AF346CFF4}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox/AvaloniaTokenizingTextBox.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Library
4 | net8.0
5 | enable
6 | True
7 | True
8 |
9 |
10 |
11 | MSBuild:Compile
12 |
13 |
14 | MSBuild:Compile
15 |
16 |
17 | MSBuild:Compile
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox/Controls/StretchChild.cs:
--------------------------------------------------------------------------------
1 | namespace AvaloniaTokenizingTextBox.Controls;
2 |
3 | public enum StretchChild
4 | {
5 | ///
6 | /// Don't apply any additional stretching logic
7 | ///
8 | None,
9 |
10 | ///
11 | /// Make the last child stretch to fill the available space
12 | ///
13 | Last
14 | }
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox/Controls/TokenTextBox.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Controls;
2 | using Avalonia.Input;
3 |
4 | namespace AvaloniaTokenizingTextBox.Controls;
5 |
6 | ///
7 | ///
8 | /// Implements ,
9 | ///
10 | ///
11 | /// As the KeyDown event doesn't seem to fire if the caret position
12 | /// of the TextBox is at the start of the control. Created inherited
13 | /// TextBox control that fires that extra event for us.
14 | ///
15 | ///
16 | ///
17 | public sealed class TokenTextBox : TextBox
18 | {
19 | protected override Type StyleKeyOverride => typeof(TextBox);
20 |
21 | public event EventHandler? BackKeyDown;
22 |
23 | protected override void OnKeyDown(KeyEventArgs e)
24 | {
25 | //If backspace is pressed while the caret position of the TextBox is 0
26 | //the event doesn't fire? So we raise our own event.
27 | OnBackKeyDown(e);
28 | base.OnKeyDown(e);
29 | }
30 |
31 | private void OnBackKeyDown(KeyEventArgs e)
32 | {
33 | BackKeyDown?.Invoke(this, e);
34 | }
35 | }
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox/Controls/TokenizingTextBox.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.ObjectModel;
3 | using System.Diagnostics;
4 | using Avalonia;
5 | using Avalonia.Controls;
6 | using Avalonia.Controls.Primitives;
7 | using Avalonia.Controls.Selection;
8 | using Avalonia.Controls.Templates;
9 | using Avalonia.Controls.Utils;
10 | using Avalonia.Data;
11 | using Avalonia.Input;
12 | using Avalonia.Interactivity;
13 | using Avalonia.Layout;
14 | using Avalonia.Metadata;
15 |
16 | namespace AvaloniaTokenizingTextBox.Controls;
17 |
18 | public class TokenDelimiter
19 | {
20 | private readonly TokenDelimiterType _delimiterType;
21 |
22 | public TokenDelimiter(TokenDelimiterType delimiterType)
23 | {
24 | _delimiterType = delimiterType;
25 | }
26 |
27 | public string? GetTypeAsString() =>
28 | _delimiterType switch
29 | {
30 | TokenDelimiterType.Semicolon => ";",
31 | TokenDelimiterType.Comma => ",",
32 | TokenDelimiterType.Pipe => "|",
33 | TokenDelimiterType.ForwardSlash => "//",
34 | TokenDelimiterType.BackSlash => "\\",
35 | TokenDelimiterType.Custom => null,
36 | _ => throw new ArgumentOutOfRangeException(nameof(_delimiterType), _delimiterType, null),
37 | };
38 |
39 | public Key? GetTypeAsKeycode() =>
40 | _delimiterType switch
41 | {
42 | TokenDelimiterType.Semicolon => (Key?)Key.OemSemicolon,
43 | TokenDelimiterType.Comma => (Key?)Key.OemComma,
44 | TokenDelimiterType.Pipe => (Key?)Key.OemPipe,
45 | TokenDelimiterType.ForwardSlash => null,
46 | TokenDelimiterType.BackSlash => (Key?)Key.OemBackslash,
47 | TokenDelimiterType.Custom => null,
48 | _ => throw new ArgumentOutOfRangeException(nameof(_delimiterType), _delimiterType, null),
49 | };
50 | }
51 |
52 | public enum TokenDelimiterType
53 | {
54 | Semicolon = 0,
55 | Comma = 1,
56 | Pipe = 2,
57 | ForwardSlash = 3,
58 | BackSlash = 4,
59 | Custom = 5
60 | }
61 |
62 | ///
63 | /// A text input control that displays tokens.
64 | ///
65 | public class TokenizingTextBox : SelectingItemsControl
66 | {
67 | private const string PART_TEXT_BOX = "PART_TextBox";
68 | private const string PART_WRAP_PANEL = "PART_WrapPanel";
69 | private const string PART_POPUP = "PART_Popup";
70 | private const string PART_SEARCH_LIST_BOX = "PART_SearchListBox";
71 |
72 | private CancellationTokenSource? _cancellationTokenSource;
73 |
74 | private ObservableCollection _searchResults;
75 | private IEnumerable _searchSource;
76 |
77 | private TokenTextBox _textBox;
78 | private WrapPanel _wrapPanel;
79 | private Popup _popup;
80 |
81 | private string _tempText = string.Empty;
82 |
83 | private ISelectionAdapter? _adapter;
84 | private object? _selectedSearchResult;
85 |
86 | ///
87 | /// The default value for the property.
88 | ///
89 | private static readonly FuncTemplate DefaultPanel =
90 | new(() => new StackPanel {Orientation = Orientation.Horizontal});
91 |
92 | ///
93 | /// Defines the property.
94 | ///
95 | public static readonly StyledProperty TokenDelimiterProperty =
96 | AvaloniaProperty.Register(
97 | nameof(TokenDelimiter),
98 | new TokenDelimiter(TokenDelimiterType.Semicolon));
99 |
100 | ///
101 | /// Defines the property.
102 | ///
103 | public static readonly StyledProperty TextProperty =
104 | TextBlock.TextProperty.AddOwner(new(
105 | coerce: (sender, value) => value,
106 | defaultBindingMode: BindingMode.TwoWay,
107 | enableDataValidation: true));
108 |
109 | ///
110 | /// Defines the property.
111 | ///
112 | public static readonly DirectProperty> SearchSourceProperty =
113 | AvaloniaProperty.RegisterDirect>(
114 | nameof(SearchSource),
115 | o => o.SearchSource,
116 | (o, v) => o.SearchSource = v);
117 |
118 | ///
119 | /// Defines the property.
120 | ///
121 | public static readonly DirectProperty> SearchResultsProperty =
122 | AvaloniaProperty.RegisterDirect>(
123 | nameof(SearchResults),
124 | o => o.SearchResults);
125 |
126 | ///
127 | /// Defines the property.
128 | ///
129 | public static readonly DirectProperty SelectedSearchResultProperty =
130 | AvaloniaProperty.RegisterDirect(
131 | nameof(SelectedSearchResult),
132 | o => o.SelectedSearchResult,
133 | (o, v) => o.SelectedSearchResult = v,
134 | defaultBindingMode: BindingMode.TwoWay,
135 | enableDataValidation: true);
136 |
137 | ///
138 | /// Gets or sets the search source.
139 | ///
140 | public IEnumerable SearchSource
141 | {
142 | get => _searchSource;
143 | set => SetAndRaise(SearchSourceProperty, ref _searchSource, value);
144 | }
145 |
146 | ///
147 | /// Gets the search results.
148 | ///
149 | public ObservableCollection SearchResults
150 | {
151 | get => _searchResults;
152 | //set => SetAndRaise(SearchResultsProperty, ref _searchResults, value);
153 | }
154 |
155 | ///
156 | /// Gets or sets the selected search result.
157 | ///
158 | public object? SelectedSearchResult
159 | {
160 | get => _selectedSearchResult;
161 | private set => SetAndRaise(SelectedSearchResultProperty, ref _selectedSearchResult, value);
162 | }
163 |
164 | ///
165 | /// Gets or sets the input text.
166 | ///
167 | [Content]
168 | public string? Text
169 | {
170 | get => GetValue(TextProperty);
171 | set => SetValue(TextProperty, value);
172 | }
173 |
174 | ///
175 | /// Gets or sets the token delimiter.
176 | ///
177 | public TokenDelimiter TokenDelimiter
178 | {
179 | get => GetValue(TokenDelimiterProperty);
180 | set => SetValue(TokenDelimiterProperty, value);
181 | }
182 |
183 | static TokenizingTextBox()
184 | {
185 | ItemsPanelProperty.OverrideDefaultValue(DefaultPanel!);
186 | TextProperty.Changed.AddClassHandler((x, e) => x.OnTextPropertyChanged(e));
187 | SelectedSearchResultProperty.Changed.AddClassHandler((x, e) => x.OnSelectedSearchResultChanged(e));
188 | }
189 |
190 | public TokenizingTextBox()
191 | {
192 | // these null!s are because those fields are set after the constructor,
193 | // but they can be considered non-nullable :-)
194 | _adapter = null;
195 | _searchResults = []; // this must be non-null
196 | _searchSource = null!;
197 | _textBox = null!;
198 | _wrapPanel = null!;
199 | _popup = null!;
200 | SelectionChanged += OnSelectionChanged;
201 | Selection = new SelectionModel();
202 | }
203 |
204 | private void OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
205 | {
206 | Debug.WriteLine($"Selection added items: {string.Join(',', e.AddedItems.Cast())}");
207 | }
208 |
209 | protected override Control CreateContainerForItemOverride(object? item, int index, object? recycleKey)
210 | {
211 | return new TokenizingTextBoxItem();
212 | }
213 |
214 | protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
215 | {
216 | return NeedsContainer(item, out recycleKey);
217 | }
218 |
219 | protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
220 | {
221 | base.OnApplyTemplate(e);
222 |
223 | if (_textBox != null && _wrapPanel != null)
224 | {
225 | _textBox.RemoveHandler(TextInputEvent, TextBox_TextChanged);
226 | _textBox.BackKeyDown -= TextBox_KeyDown;
227 | _textBox.GotFocus -= TextBox_GotFocus;
228 | _wrapPanel.KeyDown -= WrapPanel_KeyDown;
229 | }
230 |
231 | _textBox = e.NameScope.Get(PART_TEXT_BOX);
232 | _wrapPanel = e.NameScope.Get(PART_WRAP_PANEL);
233 | _popup = e.NameScope.Get(PART_POPUP);
234 | SelectionAdapter = GetSelectionAdapterPart(e.NameScope);
235 |
236 | if (_textBox != null && _wrapPanel != null)
237 | {
238 | _textBox.AddHandler(TextInputEvent, TextBox_TextChanged, RoutingStrategies.Tunnel);
239 | _textBox.BackKeyDown += TextBox_KeyDown;
240 | _textBox.GotFocus += TextBox_GotFocus;
241 | _wrapPanel.KeyDown += WrapPanel_KeyDown;
242 | }
243 | }
244 |
245 | protected override void OnPointerPressed(PointerPressedEventArgs e)
246 | {
247 | base.OnPointerPressed(e);
248 |
249 | if (e.Source is Visual source)
250 | {
251 | var point = e.GetCurrentPoint(source);
252 |
253 | if (point.Properties.IsLeftButtonPressed || point.Properties.IsRightButtonPressed)
254 | {
255 | e.Handled = UpdateSelectionFromEventSource(
256 | e.Source,
257 | true,
258 | e.KeyModifiers.HasFlag(KeyModifiers.Shift),
259 | e.KeyModifiers.HasFlag(KeyModifiers.Control),
260 | point.Properties.IsRightButtonPressed);
261 | }
262 | }
263 | }
264 |
265 | protected override void OnGotFocus(GotFocusEventArgs e)
266 | {
267 | base.OnGotFocus(e);
268 |
269 | if (e.NavigationMethod == NavigationMethod.Directional)
270 | {
271 | e.Handled = UpdateSelectionFromEventSource(
272 | e.Source,
273 | true,
274 | e.KeyModifiers.HasFlag(KeyModifiers.Shift),
275 | e.KeyModifiers.HasFlag(KeyModifiers.Control));
276 | }
277 | }
278 |
279 | private void OnSelectedSearchResultChanged(AvaloniaPropertyChangedEventArgs e)
280 | {
281 | object? newItem = e.NewValue;
282 |
283 | if (newItem != null)
284 | {
285 | _tempText = (string) newItem;
286 | }
287 | }
288 |
289 | private void OnAdapterSelectionComplete(object? sender, RoutedEventArgs e)
290 | {
291 | _textBox.Focus();
292 | string? selectedSearchItem =
293 | SelectionAdapter is SelectingItemsControlSelectionAdapter sicsa ?
294 | sicsa.SelectorControl!.SelectedValue as string :
295 | SelectionAdapter?.SelectedItem as string;
296 | if (selectedSearchItem != null)
297 | {
298 | _textBox.Text = string.Empty;
299 | _popup.IsOpen = false;
300 | AddToken(selectedSearchItem);
301 | }
302 | e.Handled = true;
303 | Debug.WriteLine("Adapter selection complete: " + selectedSearchItem);
304 | }
305 |
306 | private void OnAdapterSelectionChanged(object? sender, SelectionChangedEventArgs e)
307 | {
308 | SelectedSearchResult = SelectionAdapter?.SelectedItem;
309 | Debug.WriteLine("Adapter selection changed.");
310 | }
311 |
312 | private void OnTextPropertyChanged(AvaloniaPropertyChangedEventArgs e)
313 | {
314 | if (e.NewValue != null)
315 | {
316 | OnTextChanged((string) e.NewValue);
317 | }
318 | }
319 |
320 | private void OnTextChanged(string searchText)
321 | {
322 | _cancellationTokenSource?.Cancel();
323 | _cancellationTokenSource?.Dispose();
324 | _cancellationTokenSource = null;
325 | _cancellationTokenSource = new CancellationTokenSource();
326 |
327 | // TODO: add delay, add async search via callback / delegate
328 | var currentResults = new List(SearchResults);
329 | var newResults = FilterText(searchText, _cancellationTokenSource.Token);
330 |
331 | foreach (var str in newResults.Except(currentResults))
332 | {
333 | SearchResults.Add(str);
334 | }
335 | foreach (var str in currentResults.Except(newResults))
336 | {
337 | SearchResults.Remove(str);
338 | }
339 |
340 | _popup.IsOpen = SearchResults.Count > 0; // If we have results show the popup
341 | }
342 |
343 | private List FilterText(string searchText, CancellationToken cancellationToken)
344 | {
345 | List items = new(SearchSource); //create local copy of SearchSource property.
346 | List tokens = new((IEnumerable) ItemsSource!); //get local list of tokens already added.
347 | List results = new();
348 |
349 | foreach (string item in items)
350 | {
351 | if (cancellationToken.IsCancellationRequested)
352 | {
353 | break;
354 | }
355 |
356 | //TODO: Filter out items already in the tokens list.
357 | //TODO: Change with better method for matching
358 | if (!string.IsNullOrEmpty(searchText) && !tokens.Contains(item) && item.Contains(searchText))
359 | {
360 | results.Add(item);
361 | }
362 | }
363 | return results;
364 | }
365 |
366 | private ISelectionAdapter? SelectionAdapter
367 | {
368 | get => _adapter;
369 | set
370 | {
371 | if (_adapter != null)
372 | {
373 | _adapter.SelectionChanged -= OnAdapterSelectionChanged;
374 | _adapter.Commit -= OnAdapterSelectionComplete;
375 | _adapter.Cancel -= OnAdapterSelectionComplete;
376 | _adapter.ItemsSource = null;
377 | }
378 |
379 | _adapter = value;
380 |
381 | if (_adapter != null)
382 | {
383 | _adapter.SelectionChanged += OnAdapterSelectionChanged;
384 | _adapter.Commit += OnAdapterSelectionComplete;
385 | _adapter.Cancel += OnAdapterSelectionComplete;
386 | _adapter.ItemsSource = SearchResults;
387 | }
388 | }
389 | }
390 |
391 | private static ISelectionAdapter GetSelectionAdapterPart(INameScope nameScope)
392 | {
393 | SelectingItemsControl? selector = nameScope.Find(PART_SEARCH_LIST_BOX);
394 | if (selector != null)
395 | {
396 | // Check if it is already an IItemsSelector
397 | // Built in support for wrapping a Selector control
398 | return (selector as ISelectionAdapter) ?? new SelectingItemsControlSelectionAdapter(selector);
399 | }
400 | else
401 | {
402 | return nameScope.Find(PART_SEARCH_LIST_BOX)!;
403 | }
404 | }
405 |
406 | private void TextBox_GotFocus(object? sender, GotFocusEventArgs e)
407 | {
408 | if (!string.IsNullOrEmpty(_tempText))
409 | {
410 | Text = _tempText;
411 | _tempText = string.Empty; //Clear temp string
412 | _popup.Focus();
413 | _popup.IsOpen = false;
414 | ClearTextBoxSelection();
415 | }
416 |
417 | //Clear selection of tokens.
418 | ClearTokenSelection();
419 | }
420 |
421 | private void TextBox_KeyDown(object? sender, KeyEventArgs e)
422 | {
423 | int currentCursorPosition = _textBox.SelectionStart;
424 | int selectionLength = currentCursorPosition + _textBox.SelectionEnd;
425 | switch (e.Key)
426 | {
427 | case Key.Left when currentCursorPosition == 0 && selectionLength == 0 && ItemCount > 0:
428 | case Key.Back when currentCursorPosition == 0 && selectionLength == 0 && ItemCount > 0:
429 | var container = ContainerFromIndex(ItemCount - 1);
430 | if (container is TokenizingTextBoxItem element)
431 | {
432 | element.Focus();
433 | SelectedIndex = ItemCount - 1;
434 | }
435 |
436 | e.Handled = true;
437 | break;
438 | case Key.Escape:
439 | case Key.Back when currentCursorPosition == 1:
440 | _popup.IsOpen = false;
441 | e.Handled = true;
442 | break;
443 | // hacky solution for backspace not triggering TextBox_TextChanged
444 | case Key.Back:
445 | TextBox_TextChanged(null, new TextInputEventArgs { Text = "\b" });
446 | break;
447 | }
448 | }
449 |
450 | private void TextBox_TextChanged(object? sender, TextInputEventArgs e)
451 | {
452 | string textBoxText = _textBox.Text ?? string.Empty;
453 | string text = e.Text switch
454 | {
455 | "\b" => (textBoxText.Length > 0 ? textBoxText[0..^1] : string.Empty),
456 | null => textBoxText,
457 | _ => textBoxText + e.Text
458 | };
459 | string? tokenDelimiterStr = TokenDelimiter.GetTypeAsString();
460 |
461 | if (string.IsNullOrEmpty(text))
462 | {
463 | _popup.IsOpen = false;
464 | return;
465 | }
466 |
467 | if (tokenDelimiterStr != null && !text.Contains(tokenDelimiterStr))
468 | {
469 | // perform search and ignore tokenization
470 | OnTextChanged(text);
471 | return;
472 | }
473 |
474 | bool lastDelimited = text[^1] == tokenDelimiterStr![0];
475 |
476 | string[] tokens = text.Split(tokenDelimiterStr, StringSplitOptions.RemoveEmptyEntries);
477 | int numberToProcess = lastDelimited ? tokens.Length : tokens.Length - 1;
478 |
479 | for (var position = 0; position < numberToProcess; position++)
480 | {
481 | AddToken(tokens[position]);
482 | }
483 |
484 | if (lastDelimited)
485 | {
486 | _textBox.Text = string.Empty;
487 | }
488 | else
489 | {
490 | _textBox.Text = tokens[^1];
491 | _textBox.CaretIndex = _textBox.Text.Length;
492 | }
493 |
494 | e.Handled = true; //handle the event so the delimiter doesn't display
495 | }
496 |
497 | private void WrapPanel_KeyDown(object? sender, KeyEventArgs e)
498 | {
499 | SelectionAdapter?.HandleKeyDown(e);
500 | if (e.Handled)
501 | {
502 | return;
503 | }
504 |
505 | if (e.Key == TokenDelimiter.GetTypeAsKeycode())
506 | {
507 | e.Handled = true;
508 | _popup.Focus();
509 | _popup.IsOpen = false;
510 | _textBox.Focus();
511 | TextBox_TextChanged(null, new TextInputEventArgs { Text = TokenDelimiter.GetTypeAsString() } );
512 | return;
513 | }
514 |
515 | switch (e.Key)
516 | {
517 | case Key.Back when ItemCount > 0:
518 | case Key.Delete when ItemCount > 0 && SelectedItem != null:
519 | string selectedItem = (SelectedItem as string)!;
520 | int index = ((IList)ItemsSource!).IndexOf(selectedItem);
521 | (ItemsSource as IList)?.RemoveAt(index);
522 | _textBox.Focus();
523 | break;
524 | case Key.End when ItemCount > 0:
525 | _textBox.Focus();
526 | break;
527 | case Key.Right when ItemCount - 1 == SelectedIndex:
528 | _textBox.Focus();
529 | break;
530 | case Key.Tab:
531 | e.Handled = true;
532 | _popup.Focus();
533 | _popup.IsOpen = false;
534 | _textBox.Focus();
535 | TextBox_TextChanged(null, new TextInputEventArgs { Text = TokenDelimiter.GetTypeAsString() } );
536 | break;
537 | }
538 | }
539 |
540 | private void AddToken(string token)
541 | {
542 | if (token.Length > 0)
543 | {
544 | (ItemsSource as IList)?.Add(token);
545 | }
546 | }
547 |
548 | private void ClearTextBoxSelection()
549 | {
550 | if (_textBox != null)
551 | {
552 | int length = _textBox.Text?.Length ?? 0;
553 | _textBox.SelectionStart = length;
554 | _textBox.SelectionEnd = length;
555 | }
556 | }
557 |
558 | private void ClearTokenSelection()
559 | {
560 | SelectedIndex = -1;
561 | }
562 |
563 | ///
564 | /// Deletes a token.
565 | ///
566 | public void DeleteToken(object obj)
567 | {
568 | if (obj is string token)
569 | {
570 | // The removal should be by index,
571 | // in case there are repeated tokens.
572 | // TODO: find out how to do that
573 | ((IList)ItemsSource!).Remove(token);
574 | _textBox?.Focus();
575 | }
576 | }
577 | }
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox/Controls/TokenizingTextBoxItem.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls;
3 | using Avalonia.Controls.Metadata;
4 | using Avalonia.Controls.Mixins;
5 | using Avalonia.Controls.Primitives;
6 |
7 | namespace AvaloniaTokenizingTextBox.Controls;
8 |
9 | ///
10 | /// A control that manages as the item logic for the control.
11 | /// Implements ,
12 | /// Implements
13 | ///
14 | ///
15 | ///
16 | [PseudoClasses(":pressed", ":selected")]
17 | public class TokenizingTextBoxItem : ContentControl, ISelectable
18 | {
19 | private const string PART_BUTTON = "PART_Button";
20 | private Button? _button;
21 |
22 | ///
23 | /// Defines the property.
24 | ///
25 | public static readonly StyledProperty IsSelectedProperty =
26 | AvaloniaProperty.Register(nameof(IsSelected));
27 |
28 | ///
29 | /// Gets or sets the selection state of the item.
30 | ///
31 | public bool IsSelected
32 | {
33 | get => GetValue(IsSelectedProperty);
34 | set => SetValue(IsSelectedProperty, value);
35 | }
36 |
37 | static TokenizingTextBoxItem()
38 | {
39 | SelectableMixin.Attach(IsSelectedProperty);
40 | PressedMixin.Attach();
41 | FocusableProperty.OverrideDefaultValue(true);
42 | }
43 |
44 | protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
45 | {
46 | base.OnApplyTemplate(e);
47 |
48 | if (_button != null)
49 | {
50 | _button.Click -= Button_Click;
51 | }
52 |
53 | _button = (Button)e.NameScope.Get(PART_BUTTON);
54 |
55 | if (_button != null)
56 | {
57 | _button.Click += Button_Click;
58 | }
59 | }
60 |
61 | private void Button_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e) =>
62 | IsSelected = true;
63 | }
64 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox/Controls/TokenizingWrapPanel.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls;
3 | using Avalonia.Layout;
4 |
5 | namespace AvaloniaTokenizingTextBox.Controls;
6 |
7 | ///
8 | /// Class TokenizingWrapPanel
9 | /// Implements the
10 | /// Ported from https://github.com/iterate-ch/tokenizingtextbox
11 | ///
12 | ///
13 | public class TokenizingWrapPanel : WrapPanel
14 | {
15 | public static readonly StyledProperty HorizontalSpacingProperty =
16 | RegisterStyledProperty(nameof(HorizontalSpacing));
17 |
18 | public static readonly StyledProperty PaddingProperty =
19 | RegisterStyledProperty(nameof(Padding));
20 |
21 | public static readonly StyledProperty StretchChildProperty =
22 | RegisterStyledProperty(nameof(StretchChild));
23 |
24 | public static readonly StyledProperty VerticalSpacingProperty =
25 | RegisterStyledProperty(nameof(VerticalSpacing));
26 |
27 | public double HorizontalSpacing
28 | {
29 | get => GetValue(HorizontalSpacingProperty);
30 | set => SetValue(HorizontalSpacingProperty, value);
31 | }
32 |
33 | public Thickness Padding
34 | {
35 | get => GetValue(PaddingProperty);
36 | set => SetValue(PaddingProperty, value);
37 | }
38 |
39 | public StretchChild StretchChild
40 | {
41 | get => GetValue(StretchChildProperty);
42 | set => SetValue(StretchChildProperty, value);
43 | }
44 |
45 | public double VerticalSpacing
46 | {
47 | get => GetValue(VerticalSpacingProperty);
48 | set => SetValue(VerticalSpacingProperty, value);
49 | }
50 | private struct UvMeasure
51 | {
52 | internal static readonly UvMeasure Zero = default;
53 | internal double U { get; set; }
54 | internal double V { get; set; }
55 | public UvMeasure(Orientation orientation, double width, double height) : this()
56 | {
57 | switch (orientation)
58 | {
59 | case Orientation.Horizontal:
60 | U = width;
61 | V = height;
62 | break;
63 | case Orientation.Vertical:
64 | U = height;
65 | V = width;
66 | break;
67 | }
68 | }
69 | }
70 |
71 | protected override Size ArrangeOverride(Size finalSize)
72 | {
73 | UvMeasure parentMeasure = new(Orientation, finalSize.Width, finalSize.Height);
74 | UvMeasure spacingMeasure = new(Orientation, HorizontalSpacing, VerticalSpacing);
75 | UvMeasure paddingStart = new(Orientation, Padding.Left, Padding.Top);
76 | UvMeasure paddingEnd = new(Orientation, Padding.Right, Padding.Bottom);
77 | UvMeasure position = new(Orientation, Padding.Left, Padding.Top);
78 |
79 | double currentV = 0;
80 | void arrange(Control child, bool isLast = false)
81 | {
82 | if (child is Panel nestedPanel)
83 | {
84 | if (nestedPanel.Children.Count > 0)
85 | {
86 | int nestedIndex = nestedPanel.Children.Count;
87 | for (var i = 0; i < nestedIndex; i++)
88 | {
89 | arrange(nestedPanel.Children[i], isLast && (nestedIndex - i) == 1);
90 | }
91 | }
92 | return;
93 | }
94 |
95 | UvMeasure desiredMeasure = new(Orientation, child.DesiredSize.Width, child.DesiredSize.Height);
96 | if (desiredMeasure.U == 0)
97 | return; // if an item is collapsed, avoid adding the spacing
98 |
99 | if ((desiredMeasure.U + position.U + paddingEnd.U) > parentMeasure.U)
100 | {
101 | //next row
102 | position.U = paddingStart.U;
103 | position.V += currentV + spacingMeasure.V;
104 | currentV = 0;
105 | }
106 |
107 | // Stretch the last item to fill the available space
108 | if (isLast && StretchChild == StretchChild.Last)
109 | {
110 | desiredMeasure.U = parentMeasure.U - position.U;
111 | }
112 |
113 | // place the item
114 | child.Arrange(Orientation == Orientation.Horizontal
115 | ? new Rect(position.U, position.V, desiredMeasure.U, desiredMeasure.V)
116 | : new Rect(position.V, position.U, desiredMeasure.V, desiredMeasure.U));
117 |
118 | // adjust the location for the next items
119 | position.U += desiredMeasure.U + spacingMeasure.U;
120 | currentV = Math.Max(desiredMeasure.V, currentV);
121 | }
122 |
123 | int lastIndex = Children.Count;
124 | for (var i = 0; i < lastIndex; i++)
125 | {
126 | arrange(Children[i], (lastIndex - i) == 1);
127 | }
128 |
129 | //return base.ArrangeOverride(finalSize);
130 | return finalSize;
131 | }
132 |
133 | protected override Size MeasureOverride(Size size)
134 | {
135 | double width = size.Width - Padding.Left - Padding.Right;
136 | double height = size.Height - Padding.Top - Padding.Bottom;
137 |
138 | Size availableSize = new(width, height);
139 |
140 | UvMeasure totalMeasure = UvMeasure.Zero;
141 | UvMeasure parentMeasure = new(Orientation, availableSize.Width, availableSize.Height);
142 | UvMeasure spacingMeasure = new(Orientation, HorizontalSpacing, VerticalSpacing);
143 | UvMeasure lineMeasure = UvMeasure.Zero;
144 |
145 | void measure(Avalonia.Controls.Controls elementCollection)
146 | {
147 | foreach (Control child in elementCollection)
148 | {
149 | if (child is Panel nestedPanel)
150 | {
151 | measure(nestedPanel.Children);
152 | continue;
153 | }
154 |
155 | child.Measure(availableSize);
156 | var currentMeasure = new UvMeasure(Orientation, child.DesiredSize.Width, child.DesiredSize.Height);
157 | if (currentMeasure.U == 0)
158 | {
159 | continue; // ignore collapsed items
160 | }
161 |
162 | // if this is the first item, do not add spacing. Spacing is added to the "left"
163 | double uChange = lineMeasure.U == 0
164 | ? currentMeasure.U
165 | : currentMeasure.U + spacingMeasure.U;
166 | if (parentMeasure.U >= uChange + lineMeasure.U)
167 | {
168 | lineMeasure.U += uChange;
169 | lineMeasure.V = Math.Max(lineMeasure.V, currentMeasure.V);
170 | }
171 | else
172 | {
173 | // new line should be added
174 | // to get the max U to provide it correctly to ui width ex: ---| or -----|
175 | totalMeasure.U = Math.Max(lineMeasure.U, totalMeasure.U);
176 | totalMeasure.V += lineMeasure.V + spacingMeasure.V;
177 |
178 | // if the next new row still can handle more controls
179 | if (parentMeasure.U > currentMeasure.U)
180 | {
181 | // set lineMeasure initial values to the currentMeasure to be calculated later on the new loop
182 | lineMeasure = currentMeasure;
183 | }
184 |
185 | // the control will take one row alone
186 | else
187 | {
188 | // validate the new control measures
189 | totalMeasure.U = Math.Max(currentMeasure.U, totalMeasure.U);
190 | totalMeasure.V += currentMeasure.V;
191 |
192 | // add new empty line
193 | lineMeasure = UvMeasure.Zero;
194 | }
195 | }
196 | }
197 | }
198 | measure(Children);
199 |
200 | // update value with the last line
201 | // if the the last loop is(parentMeasure.U > currentMeasure.U + lineMeasure.U) the total isn't calculated then calculate it
202 | // if the last loop is (parentMeasure.U > currentMeasure.U) the currentMeasure isn't added to the total so add it here
203 | // for the last condition it is zeros so adding it will make no difference
204 | // this way is faster than an if condition in every loop for checking the last item
205 | totalMeasure.U = Math.Max(lineMeasure.U, totalMeasure.U);
206 | totalMeasure.V += lineMeasure.V;
207 |
208 | totalMeasure.U = Math.Ceiling(totalMeasure.U);
209 |
210 | return Orientation == Orientation.Horizontal ? new Size(totalMeasure.U, totalMeasure.V) : new Size(totalMeasure.V, totalMeasure.U);
211 | }
212 |
213 | private static StyledProperty RegisterStyledProperty(string name)
214 | {
215 | #pragma warning disable AVP1001 // The same AvaloniaProperty should not be registered twice
216 | var prop = AvaloniaProperty.Register(name);
217 | #pragma warning restore AVP1001 // The same AvaloniaProperty should not be registered twice
218 | prop.Changed.Subscribe(eventArgs =>
219 | {
220 | if (eventArgs.Sender is WrapPanel wp)
221 | {
222 | wp.InvalidateMeasure();
223 | wp.InvalidateArrange();
224 | }
225 | });
226 | return prop;
227 | }
228 | }
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox/Styles/Generic.xaml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox/Styles/TokenizingTextBox.xaml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 | Text
10 |
11 |
12 | Text1
13 |
14 |
15 | Test
16 |
17 |
18 |
19 |
60 |
61 |
64 |
65 |
70 |
71 |
72 |
79 |
80 |
85 |
86 |
90 |
--------------------------------------------------------------------------------
/AvaloniaTokenizingTextBox/Styles/TokenizingTextBoxItem.xaml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 | Text
8 |
9 |
10 | Text1
11 |
12 |
13 |
14 |
15 |
16 |
17 | M11.383 13.644A1.03 1.03 0 0 1 9.928 15.1L6 11.172 2.072 15.1a1.03 1.03 0 1 1-1.455-1.456l3.928-3.928L.617 5.79a1.03 1.03 0 1 1 1.455-1.456L6 8.261l3.928-3.928a1.03 1.03 0 0 1 1.455 1.456L7.455 9.716z
18 |
19 |
20 |
21 |
63 |
64 |
67 |
68 |
71 |
72 |
75 |
76 |
79 |
80 |
91 |
92 |
103 |
104 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Scott Whitney
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | AvaloniaTokenizingTextBox
2 | ============
3 | ### Current Progress
4 | 
5 |
6 | A Tokenizing TextBox for [Avalonia](https://github.com/AvaloniaUI/Avalonia), similar to the one created by [Marcus Perryman](https://github.com/marcpems) for [WindowsCommunityToolkit](https://github.com/windows-toolkit/WindowsCommunityToolkit)
7 |
8 | Based on work by [Jöran Malek](https://github.com/iterate-ch/tokenizingtextbox)
9 |
10 | ## Usage
11 |
12 | ```xml
13 |
14 |
19 |
20 | ```
21 |
22 | ## TODO
23 | * Cleanup main control file
24 | * ...pretty much an overhaul of everything
25 |
26 | ## Licence
27 |
28 | AvaloniaTokenizingTextBox is licensed under the [MIT license](https://github.com/puppetsw/AvaloniaTokenizingTextBox/blob/master/LICENSE).
29 |
30 | ## Contributing
31 |
32 | All contributions and improvements are welcome!
33 |
--------------------------------------------------------------------------------