├── .gitattributes ├── .gitignore ├── License.txt ├── Readme.md ├── Tyrrrz.WpfExtensions.Tests ├── ConverterTests.cs ├── Mocks │ └── MockEnum.cs └── Tyrrrz.WpfExtensions.Tests.csproj ├── Tyrrrz.WpfExtensions ├── AttachedProperties │ └── PlaceholderWatermarkProperty.cs ├── Behaviors │ ├── ListBoxSelectionBehavior.cs │ ├── ScrollBubblingBehavior.cs │ ├── TextBoxLinesBehavior.cs │ ├── TextBoxNumericInputBehavior.cs │ └── TreeViewSelectionBehavior.cs ├── Converters │ ├── ArrayToStringConverter.cs │ ├── BoolAndMultiConverter.cs │ ├── BoolOrMultiConverter.cs │ ├── BoolToVisibilityConverter.cs │ ├── BoolXorMultiConverter.cs │ ├── ByteArrayToImageConverter.cs │ ├── ByteArrayToStringConverter.cs │ ├── ColorToBrushConverter.cs │ ├── EnumToStringConverter.cs │ ├── InvertBoolConverter.cs │ ├── InvertBoolToVisibilityConverter.cs │ ├── TimeSpanToDaysConverter.cs │ ├── TimeSpanToHoursConverter.cs │ ├── TimeSpanToMillisecondsConverter.cs │ ├── TimeSpanToMinutesConverter.cs │ └── TimeSpanToSecondsConverter.cs ├── ConvertersDictionary.xaml ├── Types │ └── WatermarkAdorner.cs ├── Tyrrrz.WpfExtensions.csproj └── WpfExt.cs └── WpfExtensions.sln /.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 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | 85 | # Visual Studio profiler 86 | *.psess 87 | *.vsp 88 | *.vspx 89 | *.sap 90 | 91 | # TFS 2012 Local Workspace 92 | $tf/ 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | *.DotSettings.user 101 | 102 | # JustCode is a .NET coding add-in 103 | .JustCode 104 | 105 | # TeamCity is a build add-in 106 | _TeamCity* 107 | 108 | # DotCover is a Code Coverage Tool 109 | *.dotCover 110 | 111 | # NCrunch 112 | _NCrunch_* 113 | .*crunch*.local.xml 114 | nCrunchTemp_* 115 | 116 | # MightyMoose 117 | *.mm.* 118 | AutoTest.Net/ 119 | 120 | # Web workbench (sass) 121 | .sass-cache/ 122 | 123 | # Installshield output folder 124 | [Ee]xpress/ 125 | 126 | # DocProject is a documentation generator add-in 127 | DocProject/buildhelp/ 128 | DocProject/Help/*.HxT 129 | DocProject/Help/*.HxC 130 | DocProject/Help/*.hhc 131 | DocProject/Help/*.hhk 132 | DocProject/Help/*.hhp 133 | DocProject/Help/Html2 134 | DocProject/Help/html 135 | 136 | # Click-Once directory 137 | publish/ 138 | 139 | # Publish Web Output 140 | *.[Pp]ublish.xml 141 | *.azurePubxml 142 | 143 | # TODO: Un-comment the next line if you do not want to checkin 144 | # your web deploy settings because they may include unencrypted 145 | # passwords 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # NuGet Packages 150 | *.nupkg 151 | # The packages folder can be ignored because of Package Restore 152 | **/packages/* 153 | # except build/, which is used as an MSBuild target. 154 | !**/packages/build/ 155 | # Uncomment if necessary however generally it will be regenerated when needed 156 | #!**/packages/repositories.config 157 | # NuGet v3's project.json files produces more ignoreable files 158 | *.nuget.props 159 | *.nuget.targets 160 | 161 | # Microsoft Azure Build Output 162 | csx/ 163 | *.build.csdef 164 | 165 | # Microsoft Azure Emulator 166 | ecf/ 167 | rcf/ 168 | 169 | # Windows Store app package directory 170 | AppPackages/ 171 | BundleArtifacts/ 172 | 173 | # Visual Studio cache files 174 | # files ending in .cache can be ignored 175 | *.[Cc]ache 176 | # but keep track of directories ending in .cache 177 | !*.[Cc]ache/ 178 | 179 | # Others 180 | ClientBin/ 181 | [Ss]tyle[Cc]op.* 182 | ~$* 183 | *~ 184 | *.dbmdl 185 | *.dbproj.schemaview 186 | *.pfx 187 | *.publishsettings 188 | node_modules/ 189 | orleans.codegen.cs 190 | 191 | # RIA/Silverlight projects 192 | Generated_Code/ 193 | 194 | # Backup & report files from converting an old project file 195 | # to a newer Visual Studio version. Backup files are not needed, 196 | # because we have git ;-) 197 | _UpgradeReport_Files/ 198 | Backup*/ 199 | UpgradeLog*.XML 200 | UpgradeLog*.htm 201 | 202 | # SQL Server files 203 | *.mdf 204 | *.ldf 205 | 206 | # Business Intelligence projects 207 | *.rdl.data 208 | *.bim.layout 209 | *.bim_*.settings 210 | 211 | # Microsoft Fakes 212 | FakesAssemblies/ 213 | 214 | # GhostDoc plugin setting file 215 | *.GhostDoc.xml 216 | 217 | # Node.js Tools for Visual Studio 218 | .ntvs_analysis.dat 219 | 220 | # Visual Studio 6 build log 221 | *.plg 222 | 223 | # Visual Studio 6 workspace options file 224 | *.opt 225 | 226 | # Visual Studio LightSwitch build output 227 | **/*.HTMLClient/GeneratedArtifacts 228 | **/*.DesktopClient/GeneratedArtifacts 229 | **/*.DesktopClient/ModelManifest.xml 230 | **/*.Server/GeneratedArtifacts 231 | **/*.Server/ModelManifest.xml 232 | _Pvt_Extensions 233 | 234 | # LightSwitch generated files 235 | GeneratedArtifacts/ 236 | ModelManifest.xml 237 | 238 | # Paket dependency manager 239 | .paket/paket.exe 240 | 241 | # FAKE - F# Make 242 | .fake/ 243 | -------------------------------------------------------------------------------- /License.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016-2019 Alexey Golub 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. -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Tyrrrz.WpfExtensions 2 | 3 | My WPF Extensions 4 | 5 | ## Download 6 | 7 | - [NuGet](https://nuget.org/packages/Tyrrrz.WpfExtensions): `Install-Package Tyrrrz.WpfExtensions` 8 | -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions.Tests/ConverterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Windows; 5 | using System.Windows.Media; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | using Tyrrrz.WpfExtensions.Converters; 8 | using Tyrrrz.WpfExtensions.Tests.Mocks; 9 | 10 | namespace Tyrrrz.WpfExtensions.Tests 11 | { 12 | [TestClass] 13 | public class ConverterTests 14 | { 15 | private readonly CultureInfo _cult = CultureInfo.InvariantCulture; 16 | 17 | [TestMethod] 18 | public void ArrayToStringConverterTest() 19 | { 20 | var conv = new ArrayToStringConverter(); 21 | 22 | var a = new[] {"asd", "qwe", "zzz"}; 23 | var b = new[] {1, 2, 3}; 24 | 25 | var aForward = conv.Convert(a, null, ";", _cult) as string; 26 | var bForward = conv.Convert(b, null, null, _cult) as string; 27 | 28 | Assert.IsNotNull(aForward); 29 | Assert.AreEqual("asd;qwe;zzz", aForward); 30 | Assert.IsNotNull(bForward); 31 | Assert.AreEqual("1, 2, 3", bForward); 32 | 33 | var aBack = conv.ConvertBack(aForward, null, ";", _cult) as string[]; 34 | var bBack = conv.ConvertBack(bForward, null, null, _cult) as string[]; 35 | 36 | Assert.IsNotNull(aBack); 37 | CollectionAssert.AreEqual(a, aBack); 38 | Assert.IsNotNull(bBack); 39 | CollectionAssert.AreEqual(b, bBack.Select(int.Parse).ToArray()); 40 | } 41 | 42 | [TestMethod] 43 | public void BoolAndMultiConverterTest() 44 | { 45 | var conv = new BoolAndMultiConverter(); 46 | 47 | var a = new object[] {true, true, true}; 48 | var b = new object[] {true, false, false}; 49 | var c = new object[] {false, false, false}; 50 | 51 | var aForward = (bool) conv.Convert(a, null, null, _cult); 52 | var bForward = (bool) conv.Convert(b, null, null, _cult); 53 | var cForward = (bool) conv.Convert(c, null, null, _cult); 54 | 55 | Assert.IsTrue(aForward); 56 | Assert.IsFalse(bForward); 57 | Assert.IsFalse(cForward); 58 | 59 | // Back conversion doesn't matter 60 | } 61 | 62 | [TestMethod] 63 | public void BoolOrMultiConverterTest() 64 | { 65 | var conv = new BoolOrMultiConverter(); 66 | 67 | var a = new object[] {true, true, true}; 68 | var b = new object[] {true, false, false}; 69 | var c = new object[] {false, false, false}; 70 | 71 | var aForward = (bool) conv.Convert(a, null, null, _cult); 72 | var bForward = (bool) conv.Convert(b, null, null, _cult); 73 | var cForward = (bool) conv.Convert(c, null, null, _cult); 74 | 75 | Assert.IsTrue(aForward); 76 | Assert.IsTrue(bForward); 77 | Assert.IsFalse(cForward); 78 | 79 | // Back conversion doesn't matter 80 | } 81 | 82 | [TestMethod] 83 | public void BoolXorMultiConverterTest() 84 | { 85 | var conv = new BoolXorMultiConverter(); 86 | 87 | var a = new object[] {true, true, true}; 88 | var b = new object[] {true, false, false}; 89 | var c = new object[] {false, false, false}; 90 | 91 | var aForward = (bool) conv.Convert(a, null, null, _cult); 92 | var bForward = (bool) conv.Convert(b, null, null, _cult); 93 | var cForward = (bool) conv.Convert(c, null, null, _cult); 94 | 95 | Assert.IsFalse(aForward); 96 | Assert.IsTrue(bForward); 97 | Assert.IsFalse(cForward); 98 | 99 | // Back conversion doesn't matter 100 | } 101 | 102 | [TestMethod] 103 | public void BoolToVisibilityConverterTest() 104 | { 105 | // ReSharper disable PossibleNullReferenceException 106 | var conv = new BoolToVisibilityConverter(); 107 | 108 | var trueForward = (Visibility) conv.Convert(true, null, null, _cult); 109 | var falseForward = (Visibility) conv.Convert(false, null, null, _cult); 110 | var falseForwardCollapsed = (Visibility) conv.Convert(false, null, Visibility.Collapsed, _cult); 111 | 112 | Assert.AreEqual(Visibility.Visible, trueForward); 113 | Assert.AreEqual(Visibility.Hidden, falseForward); 114 | Assert.AreEqual(Visibility.Collapsed, falseForwardCollapsed); 115 | 116 | var trueBack = (bool) conv.ConvertBack(trueForward, null, null, _cult); 117 | var falseBack = (bool) conv.ConvertBack(falseForward, null, null, _cult); 118 | var falseBackCollapsed = (bool) conv.ConvertBack(falseForwardCollapsed, null, Visibility.Collapsed, _cult); 119 | 120 | Assert.IsTrue(trueBack); 121 | Assert.IsFalse(falseBack); 122 | Assert.IsFalse(falseBackCollapsed); 123 | // ReSharper restore PossibleNullReferenceException 124 | } 125 | 126 | [TestMethod] 127 | public void ByteArrayToImageConverterTest() 128 | { 129 | var conv = new ByteArrayToImageConverter(); 130 | 131 | var bytes = 132 | Convert.FromBase64String( 133 | "R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="); 134 | 135 | var bytesForward = conv.Convert(bytes, null, null, _cult) as ImageSource; 136 | 137 | Assert.IsNotNull(bytesForward); 138 | Assert.AreEqual(15, bytesForward.Height); 139 | Assert.AreEqual(15, bytesForward.Width); 140 | 141 | // Back conversion doesn't matter 142 | } 143 | 144 | [TestMethod] 145 | public void ByteArrayToStringConverterTest() 146 | { 147 | var conv = new ByteArrayToStringConverter(); 148 | 149 | var bytes = Convert.FromBase64String("SGVsbG8gd29ybGQ="); 150 | 151 | var bytesForward = conv.Convert(bytes, null, null, _cult) as string; 152 | 153 | Assert.AreEqual("Hello world", bytesForward); 154 | 155 | var bytesBack = conv.ConvertBack(bytesForward, null, null, _cult) as byte[]; 156 | 157 | CollectionAssert.AreEqual(bytes, bytesBack); 158 | } 159 | 160 | [TestMethod] 161 | public void ColorToBrushConverterTest() 162 | { 163 | // ReSharper disable PossibleNullReferenceException 164 | var conv = new ColorToBrushConverter(); 165 | 166 | var color = Colors.Red; 167 | 168 | var colorForward = conv.Convert(color, null, null, _cult) as Brush; 169 | 170 | Assert.IsNotNull(colorForward); 171 | 172 | var colorBack = (Color) conv.ConvertBack(colorForward, null, null, _cult); 173 | 174 | Assert.AreEqual(color, colorBack); 175 | // ReSharper restore PossibleNullReferenceException 176 | } 177 | 178 | [TestMethod] 179 | public void EnumToStringConverterTest() 180 | { 181 | var conv = new EnumToStringConverter(); 182 | 183 | var a = MockEnum.Simple; 184 | var b = MockEnum.MultipleWordsInTheName; 185 | 186 | var aForward = conv.Convert(a, typeof(MockEnum), null, _cult) as string; 187 | var bForward = conv.Convert(b, typeof(MockEnum), null, _cult) as string; 188 | 189 | Assert.AreEqual("Simple", aForward); 190 | Assert.AreEqual("Multiple Words In The Name", bForward); 191 | 192 | var aBack = conv.ConvertBack(aForward, typeof(MockEnum), null, _cult); 193 | var bBack = conv.ConvertBack(bForward, typeof(MockEnum), null, _cult); 194 | 195 | Assert.AreEqual(a, aBack); 196 | Assert.AreEqual(b, bBack); 197 | } 198 | 199 | [TestMethod] 200 | public void InvertBoolConverterTest() 201 | { 202 | // ReSharper disable PossibleNullReferenceException 203 | var conv = new InvertBoolConverter(); 204 | 205 | var trueForward = (bool) conv.Convert(true, null, null, _cult); 206 | var falseForward = (bool) conv.Convert(false, null, null, _cult); 207 | 208 | Assert.IsFalse(trueForward); 209 | Assert.IsTrue(falseForward); 210 | 211 | var trueBack = (bool) conv.ConvertBack(false, null, null, _cult); 212 | var falseBack = (bool) conv.ConvertBack(true, null, null, _cult); 213 | 214 | Assert.IsTrue(trueBack); 215 | Assert.IsFalse(falseBack); 216 | // ReSharper restore PossibleNullReferenceException 217 | } 218 | 219 | [TestMethod] 220 | public void InvertBoolToVisibilityConverterTest() 221 | { 222 | // ReSharper disable PossibleNullReferenceException 223 | var conv = new InvertBoolToVisibilityConverter(); 224 | 225 | var trueForward = (Visibility) conv.Convert(true, null, null, _cult); 226 | var trueForwardCollapsed = (Visibility) conv.Convert(true, null, Visibility.Collapsed, _cult); 227 | var falseForward = (Visibility) conv.Convert(false, null, null, _cult); 228 | 229 | Assert.AreEqual(Visibility.Hidden, trueForward); 230 | Assert.AreEqual(Visibility.Collapsed, trueForwardCollapsed); 231 | Assert.AreEqual(Visibility.Visible, falseForward); 232 | 233 | var trueBack = (bool) conv.ConvertBack(trueForward, null, null, _cult); 234 | var trueBackCollapsed = (bool) conv.ConvertBack(trueForwardCollapsed, null, Visibility.Collapsed, _cult); 235 | var falseBack = (bool) conv.ConvertBack(falseForward, null, null, _cult); 236 | 237 | Assert.IsTrue(trueBack); 238 | Assert.IsTrue(trueBackCollapsed); 239 | Assert.IsFalse(falseBack); 240 | // ReSharper restore PossibleNullReferenceException 241 | } 242 | 243 | [TestMethod] 244 | public void TimeSpanToDaysConverterTest() 245 | { 246 | // ReSharper disable PossibleNullReferenceException 247 | var conv = new TimeSpanToDaysConverter(); 248 | 249 | var ts = new TimeSpan(5, 0, 0, 0); 250 | 251 | var tsForward = (double) conv.Convert(ts, null, null, _cult); 252 | 253 | Assert.AreEqual(5, tsForward, 10e-10); 254 | 255 | var tsBack = (TimeSpan) conv.ConvertBack(tsForward, null, null, _cult); 256 | 257 | Assert.AreEqual(ts, tsBack); 258 | // ReSharper restore PossibleNullReferenceException 259 | } 260 | 261 | [TestMethod] 262 | public void TimeSpanToHoursConverterTest() 263 | { 264 | // ReSharper disable PossibleNullReferenceException 265 | var conv = new TimeSpanToHoursConverter(); 266 | 267 | var ts = new TimeSpan(5, 0, 0, 0); 268 | 269 | var tsForward = (double) conv.Convert(ts, null, null, _cult); 270 | 271 | Assert.AreEqual(5 * 24, tsForward, 10e-10); 272 | 273 | var tsBack = (TimeSpan) conv.ConvertBack(tsForward, null, null, _cult); 274 | 275 | Assert.AreEqual(ts, tsBack); 276 | // ReSharper restore PossibleNullReferenceException 277 | } 278 | 279 | [TestMethod] 280 | public void TimeSpanToMinutesConverterTest() 281 | { 282 | // ReSharper disable PossibleNullReferenceException 283 | var conv = new TimeSpanToMinutesConverter(); 284 | 285 | var ts = new TimeSpan(5, 0, 0, 0); 286 | 287 | var tsForward = (double) conv.Convert(ts, null, null, _cult); 288 | 289 | Assert.AreEqual(5 * 24 * 60, tsForward, 10e-10); 290 | 291 | var tsBack = (TimeSpan) conv.ConvertBack(tsForward, null, null, _cult); 292 | 293 | Assert.AreEqual(ts, tsBack); 294 | // ReSharper restore PossibleNullReferenceException 295 | } 296 | 297 | [TestMethod] 298 | public void TimeSpanToSecondsConverterTest() 299 | { 300 | // ReSharper disable PossibleNullReferenceException 301 | var conv = new TimeSpanToSecondsConverter(); 302 | 303 | var ts = new TimeSpan(5, 0, 0, 0); 304 | 305 | var tsForward = (double) conv.Convert(ts, null, null, _cult); 306 | 307 | Assert.AreEqual(5 * 24 * 60 * 60, tsForward, 10e-10); 308 | 309 | var tsBack = (TimeSpan) conv.ConvertBack(tsForward, null, null, _cult); 310 | 311 | Assert.AreEqual(ts, tsBack); 312 | // ReSharper restore PossibleNullReferenceException 313 | } 314 | 315 | [TestMethod] 316 | public void TimeSpanToMillisecondsConverterTest() 317 | { 318 | // ReSharper disable PossibleNullReferenceException 319 | var conv = new TimeSpanToMillisecondsConverter(); 320 | 321 | var ts = new TimeSpan(5, 0, 0, 0); 322 | 323 | var tsForward = (double) conv.Convert(ts, null, null, _cult); 324 | 325 | Assert.AreEqual(5 * 24 * 60 * 60 * 1000, tsForward, 10e-10); 326 | 327 | var tsBack = (TimeSpan) conv.ConvertBack(tsForward, null, null, _cult); 328 | 329 | Assert.AreEqual(ts, tsBack); 330 | // ReSharper restore PossibleNullReferenceException 331 | } 332 | } 333 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions.Tests/Mocks/MockEnum.cs: -------------------------------------------------------------------------------- 1 | namespace Tyrrrz.WpfExtensions.Tests.Mocks 2 | { 3 | public enum MockEnum 4 | { 5 | Simple, 6 | MultipleWordsInTheName 7 | } 8 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions.Tests/Tyrrrz.WpfExtensions.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net45 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/AttachedProperties/PlaceholderWatermarkProperty.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Linq; 5 | using System.Windows; 6 | using System.Windows.Controls; 7 | using System.Windows.Controls.Primitives; 8 | using System.Windows.Documents; 9 | using Tyrrrz.WpfExtensions.Types; 10 | 11 | namespace Tyrrrz.WpfExtensions.AttachedProperties 12 | { 13 | /// 14 | /// Attached property that allows display of a watermark as a placeholder for control's content 15 | /// 16 | public static class PlaceholderWatermarkProperty 17 | { 18 | /// 19 | /// Watermark Attached Dependency Property 20 | /// 21 | public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached( 22 | "Watermark", 23 | typeof(object), 24 | typeof(PlaceholderWatermarkProperty), 25 | new FrameworkPropertyMetadata(null, OnWatermarkChanged)); 26 | 27 | 28 | /// 29 | /// Dictionary of ItemsControls 30 | /// 31 | private static Dictionary ItemsControls { get; } = new Dictionary(); 32 | 33 | /// 34 | /// Gets the Watermark property. This dependency property indicates the watermark for the control. 35 | /// 36 | /// to get the property from 37 | /// The value of the Watermark property 38 | public static object GetWatermark(DependencyObject d) 39 | { 40 | return d.GetValue(WatermarkProperty); 41 | } 42 | 43 | /// 44 | /// Sets the Watermark property. This dependency property indicates the watermark for the control. 45 | /// 46 | /// to set the property on 47 | /// value of the property 48 | public static void SetWatermark(DependencyObject d, object value) 49 | { 50 | d.SetValue(WatermarkProperty, value); 51 | } 52 | 53 | /// 54 | /// Handles changes to the Watermark property. 55 | /// 56 | /// that fired the event 57 | /// A that contains the event data. 58 | private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 59 | { 60 | var control = (Control)d; 61 | control.Loaded += Control_Loaded; 62 | 63 | if (d is ComboBox || d is TextBox) 64 | { 65 | control.GotKeyboardFocus += Control_GotKeyboardFocus; 66 | control.LostKeyboardFocus += Control_Loaded; 67 | } 68 | 69 | var itemsControl = d as ItemsControl; 70 | if (itemsControl != null && !(d is ComboBox)) 71 | { 72 | // for Items property 73 | itemsControl.ItemContainerGenerator.ItemsChanged += ItemsChanged; 74 | ItemsControls.Add(itemsControl.ItemContainerGenerator, itemsControl); 75 | 76 | // for ItemsSource property 77 | var prop = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, itemsControl.GetType()); 78 | prop.AddValueChanged(itemsControl, ItemsSourceChanged); 79 | } 80 | } 81 | 82 | /// 83 | /// Handle the GotFocus event on the control 84 | /// 85 | /// The source of the event. 86 | /// A that contains the event data. 87 | private static void Control_GotKeyboardFocus(object sender, RoutedEventArgs e) 88 | { 89 | var c = (Control) sender; 90 | if (ShouldShowWatermark(c)) 91 | RemoveWatermark(c); 92 | } 93 | 94 | /// 95 | /// Handle the Loaded and LostFocus event on the control 96 | /// 97 | /// The source of the event. 98 | /// A that contains the event data. 99 | private static void Control_Loaded(object sender, RoutedEventArgs e) 100 | { 101 | var control = (Control) sender; 102 | if (ShouldShowWatermark(control)) 103 | ShowWatermark(control); 104 | } 105 | 106 | /// 107 | /// Event handler for the items source changed event 108 | /// 109 | /// The source of the event. 110 | /// A that contains the event data. 111 | private static void ItemsSourceChanged(object sender, EventArgs e) 112 | { 113 | var c = (ItemsControl) sender; 114 | if (c.ItemsSource != null) 115 | { 116 | if (ShouldShowWatermark(c)) 117 | ShowWatermark(c); 118 | else 119 | RemoveWatermark(c); 120 | } 121 | else 122 | { 123 | ShowWatermark(c); 124 | } 125 | } 126 | 127 | /// 128 | /// Event handler for the items changed event 129 | /// 130 | /// The source of the event. 131 | /// A that contains the event data. 132 | private static void ItemsChanged(object sender, ItemsChangedEventArgs e) 133 | { 134 | ItemsControl control; 135 | if (!ItemsControls.TryGetValue(sender, out control)) return; 136 | 137 | if (ShouldShowWatermark(control)) 138 | ShowWatermark(control); 139 | else 140 | RemoveWatermark(control); 141 | } 142 | 143 | 144 | /// 145 | /// Remove the watermark from the specified element 146 | /// 147 | /// Element to remove the watermark from 148 | private static void RemoveWatermark(UIElement control) 149 | { 150 | var layer = AdornerLayer.GetAdornerLayer(control); 151 | 152 | // Get adorners 153 | var adorners = layer?.GetAdorners(control); 154 | if (adorners == null) return; 155 | 156 | foreach (var adorner in adorners.OfType()) 157 | { 158 | adorner.Visibility = Visibility.Hidden; 159 | layer.Remove(adorner); 160 | } 161 | } 162 | 163 | /// 164 | /// Show the watermark on the specified control 165 | /// 166 | /// Control to show the watermark on 167 | private static void ShowWatermark(UIElement control) 168 | { 169 | var layer = AdornerLayer.GetAdornerLayer(control); 170 | layer?.Add(new WatermarkAdorner(control, GetWatermark(control))); 171 | } 172 | 173 | /// 174 | /// Indicates whether or not the watermark should be shown on the specified control 175 | /// 176 | /// to test 177 | /// true if the watermark should be shown; false otherwise 178 | private static bool ShouldShowWatermark(Control c) 179 | { 180 | var comboBox = c as ComboBox; 181 | var textBox = c as TextBox; 182 | var itemsControl = c as ItemsControl; 183 | 184 | if (comboBox != null) 185 | return comboBox.Text == string.Empty; 186 | if (textBox != null) 187 | return textBox.Text == string.Empty; 188 | return itemsControl?.Items.Count == 0; 189 | } 190 | } 191 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Behaviors/ListBoxSelectionBehavior.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Specialized; 3 | using System.Linq; 4 | using System.Windows; 5 | using System.Windows.Controls; 6 | using System.Windows.Interactivity; 7 | 8 | namespace Tyrrrz.WpfExtensions.Behaviors 9 | { 10 | /// 11 | /// Allows two way binding on SelectedItems proprety of a ListBox 12 | /// 13 | public class ListBoxSelectionBehavior : Behavior 14 | { 15 | #region Static 16 | 17 | /// 18 | /// SelectedItems dependency property 19 | /// 20 | public static readonly DependencyProperty SelectedItemsProperty = 21 | DependencyProperty.Register(nameof(SelectedItems), typeof(IList), 22 | typeof(ListBoxSelectionBehavior), 23 | new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 24 | OnSelectedItemsChanged)); 25 | 26 | /// 27 | /// SelectedValues dependency property 28 | /// 29 | public static readonly DependencyProperty SelectedValuesProperty = 30 | DependencyProperty.Register(nameof(SelectedValues), typeof(IList), 31 | typeof(ListBoxSelectionBehavior), 32 | new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 33 | OnSelectedValuesChanged)); 34 | 35 | /// 36 | /// Called when selected items property is changed from binding source 37 | /// 38 | private static void OnSelectedItemsChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) 39 | { 40 | var behavior = (ListBoxSelectionBehavior) sender; 41 | if (behavior._modelHandled) return; 42 | 43 | if (behavior.AssociatedObject == null) 44 | return; 45 | 46 | behavior._modelHandled = true; 47 | behavior.SelectedItemsToValues(); 48 | behavior.SelectItems(); 49 | behavior._modelHandled = false; 50 | } 51 | 52 | /// 53 | /// Called when selected items property is changed from binding source 54 | /// 55 | private static void OnSelectedValuesChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) 56 | { 57 | var behavior = (ListBoxSelectionBehavior) sender; 58 | if (behavior._modelHandled) return; 59 | 60 | if (behavior.AssociatedObject == null) 61 | return; 62 | 63 | behavior._modelHandled = true; 64 | behavior.SelectedValuesToItems(); 65 | behavior.SelectItems(); 66 | behavior._modelHandled = false; 67 | } 68 | 69 | private static object GetDeepPropertyValue(object obj, string path) 70 | { 71 | if (string.IsNullOrWhiteSpace(path)) return obj; 72 | while (true) 73 | { 74 | if (path.Contains('.')) 75 | { 76 | var split = path.Split('.'); 77 | var remainingProperty = path.Substring(path.IndexOf('.') + 1); 78 | obj = obj?.GetType().GetProperty(split[0])?.GetValue(obj, null); 79 | path = remainingProperty; 80 | continue; 81 | } 82 | return obj?.GetType().GetProperty(path)?.GetValue(obj, null); 83 | } 84 | } 85 | 86 | #endregion 87 | 88 | private bool _viewHandled; 89 | private bool _modelHandled; 90 | 91 | /// 92 | /// Bindable selected items array 93 | /// 94 | public IList SelectedItems 95 | { 96 | get => (IList) GetValue(SelectedItemsProperty); 97 | set => SetValue(SelectedItemsProperty, value); 98 | } 99 | 100 | /// 101 | /// Bindable selected values array 102 | /// 103 | public IList SelectedValues 104 | { 105 | get => (IList) GetValue(SelectedValuesProperty); 106 | set => SetValue(SelectedValuesProperty, value); 107 | } 108 | 109 | /// 110 | /// Selects items in listbox, based on the SelectedItems property 111 | /// 112 | private void SelectItems() 113 | { 114 | _viewHandled = true; 115 | AssociatedObject.SelectedItems.Clear(); 116 | if (SelectedItems != null) 117 | { 118 | foreach (var item in SelectedItems) 119 | AssociatedObject.SelectedItems.Add(item); 120 | } 121 | _viewHandled = false; 122 | } 123 | 124 | /// 125 | /// Updates SelectedItems based on SelectedValues 126 | /// 127 | private void SelectedValuesToItems() 128 | { 129 | if (SelectedValues == null) 130 | SelectedItems = null; 131 | else 132 | SelectedItems = 133 | AssociatedObject.Items.Cast() 134 | .Where(i => SelectedValues.Contains(GetDeepPropertyValue(i, AssociatedObject.SelectedValuePath))) 135 | .ToArray(); 136 | } 137 | 138 | /// 139 | /// Updates SelectedValues based on SelectedItems 140 | /// 141 | private void SelectedItemsToValues() 142 | { 143 | if (SelectedItems == null) 144 | SelectedValues = null; 145 | else 146 | SelectedValues = 147 | SelectedItems.Cast() 148 | .Select(i => GetDeepPropertyValue(i, AssociatedObject.SelectedValuePath)) 149 | .ToArray(); 150 | } 151 | 152 | /// 153 | /// Called when list box selection changes from view 154 | /// 155 | private void OnListBoxSelectionChanged(object sender, SelectionChangedEventArgs selectionChangedEventArgs) 156 | { 157 | if (_viewHandled) return; 158 | if (AssociatedObject.Items.SourceCollection == null) return; 159 | SelectedItems = AssociatedObject.SelectedItems.Cast().ToArray(); 160 | } 161 | 162 | /// 163 | /// Called when list box items change 164 | /// 165 | private void OnListBoxItemsChanged(object sender, NotifyCollectionChangedEventArgs e) 166 | { 167 | if (_viewHandled) return; 168 | if (AssociatedObject.Items.SourceCollection == null) return; 169 | SelectItems(); 170 | } 171 | 172 | /// 173 | protected override void OnAttached() 174 | { 175 | base.OnAttached(); 176 | 177 | AssociatedObject.SelectionChanged += OnListBoxSelectionChanged; 178 | ((INotifyCollectionChanged) AssociatedObject.Items).CollectionChanged += OnListBoxItemsChanged; 179 | 180 | _modelHandled = true; 181 | SelectedValuesToItems(); 182 | SelectItems(); 183 | _modelHandled = false; 184 | } 185 | 186 | /// 187 | protected override void OnDetaching() 188 | { 189 | base.OnDetaching(); 190 | 191 | if (AssociatedObject != null) 192 | { 193 | AssociatedObject.SelectionChanged -= OnListBoxSelectionChanged; 194 | ((INotifyCollectionChanged) AssociatedObject.Items).CollectionChanged -= OnListBoxItemsChanged; 195 | } 196 | } 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Behaviors/ScrollBubblingBehavior.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | using System.Windows.Controls; 3 | using System.Windows.Input; 4 | using System.Windows.Interactivity; 5 | using System.Windows.Media; 6 | 7 | namespace Tyrrrz.WpfExtensions.Behaviors 8 | { 9 | /// 10 | /// Allows bubbling of scroll events from child to parent 11 | /// 12 | public class ScrollBubblingBehavior : Behavior 13 | { 14 | #region Static 15 | 16 | /// 17 | /// AlwaysBubble dependency property 18 | /// 19 | public static readonly DependencyProperty AlwaysBubbleProperty = 20 | DependencyProperty.Register(nameof(AlwaysBubble), typeof(bool), 21 | typeof(ScrollBubblingBehavior), 22 | new FrameworkPropertyMetadata(false)); 23 | 24 | private static T GetVisualChild(DependencyObject parent) where T : Visual 25 | { 26 | T child = null; 27 | var numVisuals = VisualTreeHelper.GetChildrenCount(parent); 28 | for (var i = 0; i < numVisuals; i++) 29 | { 30 | var v = (Visual) VisualTreeHelper.GetChild(parent, i); 31 | child = v as T ?? GetVisualChild(v); 32 | if (child != null) 33 | break; 34 | } 35 | return child; 36 | } 37 | 38 | #endregion 39 | 40 | /// 41 | /// When set to false, bubbling will only occur if the scrolling eached its limit. 42 | /// If set to true, bubbling will always occur. 43 | /// 44 | public bool AlwaysBubble 45 | { 46 | get => (bool) GetValue(AlwaysBubbleProperty); 47 | set => SetValue(AlwaysBubbleProperty, value); 48 | } 49 | 50 | private void PreviewMouseWheel(object sender, MouseWheelEventArgs e) 51 | { 52 | // Determine if there's a need to bubble 53 | bool shouldBubble; 54 | if (AlwaysBubble) 55 | { 56 | shouldBubble = true; 57 | } 58 | else 59 | { 60 | var scrollViewer = AssociatedObject as ScrollViewer ?? GetVisualChild(AssociatedObject); 61 | if (scrollViewer != null) 62 | { 63 | var scrollPos = scrollViewer.ContentVerticalOffset; 64 | shouldBubble = (scrollPos >= scrollViewer.ScrollableHeight && e.Delta < 0) || 65 | (scrollPos <= 0 && e.Delta > 0); 66 | } 67 | else 68 | { 69 | shouldBubble = true; 70 | } 71 | } 72 | if (!shouldBubble) return; 73 | 74 | // Bubble the event 75 | e.Handled = true; 76 | var bubble = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta) 77 | { 78 | RoutedEvent = UIElement.MouseWheelEvent 79 | }; 80 | AssociatedObject.RaiseEvent(bubble); 81 | } 82 | 83 | /// 84 | protected override void OnAttached() 85 | { 86 | base.OnAttached(); 87 | 88 | AssociatedObject.PreviewMouseWheel += PreviewMouseWheel; 89 | } 90 | 91 | /// 92 | protected override void OnDetaching() 93 | { 94 | base.OnDetaching(); 95 | 96 | if (AssociatedObject != null) 97 | { 98 | AssociatedObject.PreviewMouseWheel -= PreviewMouseWheel; 99 | } 100 | } 101 | } 102 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Behaviors/TextBoxLinesBehavior.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Windows; 3 | using System.Windows.Controls; 4 | using System.Windows.Interactivity; 5 | 6 | namespace Tyrrrz.WpfExtensions.Behaviors 7 | { 8 | /// 9 | /// Allows two way binding of string lines of a text box 10 | /// 11 | public class TextBoxLinesBehavior : Behavior 12 | { 13 | #region Static 14 | /// 15 | /// Lines dependency property 16 | /// 17 | public static readonly DependencyProperty LinesProperty = 18 | DependencyProperty.Register(nameof(Lines), typeof(string[]), typeof(TextBoxLinesBehavior), 19 | new FrameworkPropertyMetadata(new string[0], FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnLinesChanged)); 20 | 21 | /// 22 | /// Called when lines property is changed from binding source 23 | /// 24 | private static void OnLinesChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) 25 | { 26 | var behavior = (TextBoxLinesBehavior) sender; 27 | if (behavior._modelHandled) return; 28 | 29 | if (behavior.AssociatedObject == null) 30 | return; 31 | 32 | behavior._modelHandled = true; 33 | behavior.LinesToText(); 34 | behavior._modelHandled = false; 35 | } 36 | #endregion 37 | 38 | private bool _modelHandled; 39 | 40 | /// 41 | /// Bindable lines 42 | /// 43 | public string[] Lines 44 | { 45 | get => (string[]) GetValue(LinesProperty); 46 | set => SetValue(LinesProperty, value); 47 | } 48 | 49 | private void LinesToText() 50 | { 51 | AssociatedObject.Text = string.Join(Environment.NewLine, Lines); 52 | } 53 | 54 | private void TextToLines() 55 | { 56 | Lines = AssociatedObject.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); 57 | } 58 | 59 | private void OnTextBoxTextChanged(object sender, TextChangedEventArgs textChangedEventArgs) 60 | { 61 | if (_modelHandled) return; 62 | TextToLines(); 63 | } 64 | 65 | /// 66 | protected override void OnAttached() 67 | { 68 | base.OnAttached(); 69 | 70 | AssociatedObject.TextChanged += OnTextBoxTextChanged; 71 | 72 | _modelHandled = true; 73 | LinesToText(); 74 | _modelHandled = false; 75 | } 76 | 77 | /// 78 | protected override void OnDetaching() 79 | { 80 | base.OnDetaching(); 81 | 82 | if (AssociatedObject != null) 83 | { 84 | AssociatedObject.TextChanged -= OnTextBoxTextChanged; 85 | } 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Behaviors/TextBoxNumericInputBehavior.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using System.Text.RegularExpressions; 3 | using System.Windows; 4 | using System.Windows.Controls; 5 | using System.Windows.Input; 6 | using System.Windows.Interactivity; 7 | 8 | namespace Tyrrrz.WpfExtensions.Behaviors 9 | { 10 | /// 11 | /// Handles input and binding for textbox, intended for numeric input 12 | /// 13 | public class TextBoxNumericInputBehavior : Behavior 14 | { 15 | #region Static 16 | 17 | private static readonly Regex FloatValidationRegex = 18 | new Regex(@"[^0-9\-\+" + @"\" + NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + @"]+", 19 | RegexOptions.Compiled); 20 | 21 | private static readonly Regex IntegerValidationRegex = 22 | new Regex(@"[^0-9\-\+]+", 23 | RegexOptions.Compiled); 24 | 25 | /// 26 | /// IsFloatingPoint dependency property 27 | /// 28 | public static readonly DependencyProperty IsFloatingPointProperty = 29 | DependencyProperty.Register(nameof(IsFloatingPoint), typeof(bool), 30 | typeof(TextBoxNumericInputBehavior), 31 | new FrameworkPropertyMetadata(false)); 32 | 33 | /// 34 | /// Value (double) dependency property 35 | /// 36 | public static readonly DependencyProperty ValueDoubleProperty = 37 | DependencyProperty.Register(nameof(ValueDouble), typeof(double), 38 | typeof(TextBoxNumericInputBehavior), 39 | new FrameworkPropertyMetadata(default(double), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 40 | OnValueChanged)); 41 | 42 | /// 43 | /// Value (int) dependency property 44 | /// 45 | public static readonly DependencyProperty ValueIntProperty = 46 | DependencyProperty.Register(nameof(ValueInt), typeof(long), 47 | typeof(TextBoxNumericInputBehavior), 48 | new FrameworkPropertyMetadata(default(long), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 49 | OnValueChanged)); 50 | 51 | /// 52 | /// Called when the value property is changed from binding source 53 | /// 54 | private static void OnValueChanged(DependencyObject sender, 55 | DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) 56 | { 57 | var behavior = (TextBoxNumericInputBehavior) sender; 58 | if (behavior._modelHandled) return; 59 | 60 | if (behavior.AssociatedObject == null) 61 | return; 62 | 63 | behavior._modelHandled = true; 64 | behavior.ValueToText(); 65 | behavior._modelHandled = false; 66 | } 67 | 68 | #endregion 69 | 70 | private bool _modelHandled; 71 | 72 | /// 73 | /// Gets or sets whether the number in the textbox is a floating point number. 74 | /// When set to true, use . 75 | /// When set to false, use . 76 | /// 77 | public bool IsFloatingPoint 78 | { 79 | get => (bool) GetValue(IsFloatingPointProperty); 80 | set => SetValue(IsFloatingPointProperty, value); 81 | } 82 | 83 | /// 84 | /// Bindable numeric value of the textbox 85 | /// 86 | public double ValueDouble 87 | { 88 | get => (double) GetValue(ValueDoubleProperty); 89 | set => SetValue(ValueDoubleProperty, value); 90 | } 91 | 92 | /// 93 | /// Bindable numeric value of the textbox 94 | /// 95 | public long ValueInt 96 | { 97 | get => (long) GetValue(ValueIntProperty); 98 | set => SetValue(ValueIntProperty, value); 99 | } 100 | 101 | private void TextToValue() 102 | { 103 | // Empty text - do nothing 104 | if (string.IsNullOrWhiteSpace(AssociatedObject.Text)) 105 | return; 106 | 107 | // If ending with a decimal point - do nothing 108 | if (AssociatedObject.Text.EndsWith(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)) 109 | return; 110 | 111 | // If there is a decimal point and ending with zero - do nothing 112 | if (AssociatedObject.Text.Contains(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator) && 113 | AssociatedObject.Text.EndsWith("0")) 114 | return; 115 | 116 | // Validate text and set 117 | if (IsFloatingPoint) 118 | { 119 | double value; 120 | if (double.TryParse(AssociatedObject.Text, out value)) 121 | ValueDouble = value; 122 | } 123 | else 124 | { 125 | long value; 126 | if (long.TryParse(AssociatedObject.Text, out value)) 127 | ValueInt = value; 128 | } 129 | } 130 | 131 | private void ValueToText() 132 | { 133 | AssociatedObject.Text = IsFloatingPoint 134 | ? ValueDouble.ToString(CultureInfo.CurrentCulture) 135 | : ValueInt.ToString(CultureInfo.CurrentCulture); 136 | } 137 | 138 | private void OnTextBoxPreviewTextInput(object sender, TextCompositionEventArgs e) 139 | { 140 | // Only numbers and approved symbols accepted 141 | e.Handled = IsFloatingPoint 142 | ? FloatValidationRegex.IsMatch(e.Text) 143 | : IntegerValidationRegex.IsMatch(e.Text); 144 | } 145 | 146 | private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e) 147 | { 148 | if (_modelHandled) return; 149 | TextToValue(); 150 | } 151 | 152 | private void OnTextBoxLostFocus(object sender, RoutedEventArgs e) 153 | { 154 | ValueToText(); 155 | } 156 | 157 | /// 158 | protected override void OnAttached() 159 | { 160 | base.OnAttached(); 161 | 162 | AssociatedObject.PreviewTextInput += OnTextBoxPreviewTextInput; 163 | AssociatedObject.TextChanged += OnTextBoxTextChanged; 164 | AssociatedObject.LostFocus += OnTextBoxLostFocus; 165 | 166 | _modelHandled = true; 167 | ValueToText(); 168 | _modelHandled = false; 169 | } 170 | 171 | /// 172 | protected override void OnDetaching() 173 | { 174 | base.OnDetaching(); 175 | 176 | if (AssociatedObject != null) 177 | { 178 | AssociatedObject.PreviewTextInput -= OnTextBoxPreviewTextInput; 179 | AssociatedObject.TextChanged -= OnTextBoxTextChanged; 180 | AssociatedObject.LostFocus -= OnTextBoxLostFocus; 181 | } 182 | } 183 | } 184 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Behaviors/TreeViewSelectionBehavior.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Specialized; 2 | using System.Windows; 3 | using System.Windows.Controls; 4 | using System.Windows.Interactivity; 5 | 6 | namespace Tyrrrz.WpfExtensions.Behaviors 7 | { 8 | /// 9 | /// Allows two way binding on SelectedItem proprety of a TreeView 10 | /// 11 | public class TreeViewSelectionBehavior : Behavior 12 | { 13 | /// 14 | /// Delegate that checks whether one node is a child of another node 15 | /// (Suspected) child node 16 | /// (Suspected) parent node 17 | /// 18 | public delegate bool IsChildOfPredicate(object nodeA, object nodeB); 19 | 20 | #region Static 21 | 22 | /// 23 | /// SelectedItem dependency property 24 | /// 25 | public static readonly DependencyProperty SelectedItemProperty = 26 | DependencyProperty.Register(nameof(SelectedItem), typeof(object), 27 | typeof(TreeViewSelectionBehavior), 28 | new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 29 | OnSelectedItemChanged)); 30 | 31 | /// 32 | /// HierarchyPredicate dependency property 33 | /// 34 | public static readonly DependencyProperty HierarchyPredicateProperty = 35 | DependencyProperty.Register(nameof(HierarchyPredicate), typeof(IsChildOfPredicate), 36 | typeof(TreeViewSelectionBehavior), 37 | new FrameworkPropertyMetadata(null)); 38 | 39 | /// 40 | /// ExpandSelected dependency proprety 41 | /// 42 | public static readonly DependencyProperty ExpandSelectedProperty = 43 | DependencyProperty.Register(nameof(ExpandSelected), typeof(bool), 44 | typeof(TreeViewSelectionBehavior), 45 | new FrameworkPropertyMetadata(false)); 46 | 47 | /// 48 | /// Called when selected item property is changed from binding source 49 | /// 50 | private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) 51 | { 52 | var behavior = (TreeViewSelectionBehavior) sender; 53 | if (behavior._modelHandled) return; 54 | 55 | if (behavior.AssociatedObject == null) 56 | return; 57 | 58 | behavior._modelHandled = true; 59 | behavior.UpdateAllTreeViewItems(); 60 | behavior._modelHandled = false; 61 | } 62 | 63 | #endregion 64 | 65 | private readonly EventSetter _treeViewItemEventSetter; 66 | private bool _modelHandled; 67 | 68 | /// 69 | /// Bindable selected item 70 | /// 71 | public object SelectedItem 72 | { 73 | get => GetValue(SelectedItemProperty); 74 | set => SetValue(SelectedItemProperty, value); 75 | } 76 | 77 | /// 78 | /// Predicate that checks if one node is a child of another 79 | /// 80 | public IsChildOfPredicate HierarchyPredicate 81 | { 82 | get => (IsChildOfPredicate) GetValue(HierarchyPredicateProperty); 83 | set => SetValue(HierarchyPredicateProperty, value); 84 | } 85 | 86 | /// 87 | /// Gets or sets whether the selected item should also be expanded 88 | /// 89 | public bool ExpandSelected 90 | { 91 | get => (bool) GetValue(ExpandSelectedProperty); 92 | set => SetValue(ExpandSelectedProperty, value); 93 | } 94 | 95 | /// 96 | public TreeViewSelectionBehavior() 97 | { 98 | _treeViewItemEventSetter = new EventSetter( 99 | FrameworkElement.LoadedEvent, 100 | new RoutedEventHandler(OnTreeViewItemLoaded)); 101 | } 102 | 103 | /// 104 | /// Updates Selected and Expanded state of a single tree view item and (optionally) all its children recursively 105 | /// 106 | private void UpdateTreeViewItem(TreeViewItem item, bool recurse) 107 | { 108 | if (SelectedItem == null) return; 109 | var model = item.DataContext; 110 | 111 | // If the selected item is this model and is not yet selected - select and return 112 | if (SelectedItem == model && !item.IsSelected) 113 | { 114 | item.IsSelected = true; 115 | if (ExpandSelected) 116 | item.IsExpanded = true; 117 | } 118 | // If the selected item is a parent of this model - expand 119 | else 120 | { 121 | var isParentOfModel = HierarchyPredicate?.Invoke(SelectedItem, model) ?? true; 122 | if (isParentOfModel) 123 | item.IsExpanded = true; 124 | } 125 | 126 | // Recurse into children 127 | if (recurse) 128 | { 129 | foreach (var subitem in item.Items) 130 | { 131 | var tvi = item.ItemContainerGenerator.ContainerFromItem(subitem) as TreeViewItem; 132 | if (tvi != null) 133 | UpdateTreeViewItem(tvi, true); 134 | } 135 | } 136 | } 137 | 138 | /// 139 | /// Updates Selected and Expanded states of all items in the tree view 140 | /// 141 | private void UpdateAllTreeViewItems() 142 | { 143 | var treeView = AssociatedObject; 144 | foreach (var item in treeView.Items) 145 | { 146 | var tvi = treeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem; 147 | if (tvi != null) 148 | UpdateTreeViewItem(tvi, true); 149 | } 150 | } 151 | 152 | /// 153 | /// Updates the style of a tree view item by adding event triggers 154 | /// 155 | private void UpdateTreeViewItemStyle() 156 | { 157 | if (AssociatedObject.ItemContainerStyle == null) 158 | AssociatedObject.ItemContainerStyle = new Style( 159 | typeof(TreeViewItem), 160 | Application.Current.TryFindResource(typeof(TreeViewItem)) as Style); 161 | 162 | if (!AssociatedObject.ItemContainerStyle.Setters.Contains(_treeViewItemEventSetter)) 163 | AssociatedObject.ItemContainerStyle.Setters.Add(_treeViewItemEventSetter); 164 | } 165 | 166 | /// 167 | /// Called when items in the tree view are changed 168 | /// 169 | private void OnTreeViewItemsChanged(object sender, 170 | NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) 171 | { 172 | UpdateAllTreeViewItems(); 173 | } 174 | 175 | /// 176 | /// Called when selected item is changed from tree view itself (from UI) 177 | /// 178 | private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs e) 179 | { 180 | if (_modelHandled) return; 181 | if (AssociatedObject.Items.SourceCollection == null) return; 182 | SelectedItem = e.NewValue; 183 | } 184 | 185 | /// 186 | /// Called when a tree view item is loaded 187 | /// 188 | private void OnTreeViewItemLoaded(object sender, RoutedEventArgs e) 189 | { 190 | UpdateTreeViewItem((TreeViewItem) sender, false); 191 | } 192 | 193 | /// 194 | protected override void OnAttached() 195 | { 196 | base.OnAttached(); 197 | 198 | AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged; 199 | ((INotifyCollectionChanged) AssociatedObject.Items).CollectionChanged += OnTreeViewItemsChanged; 200 | 201 | UpdateTreeViewItemStyle(); 202 | _modelHandled = true; 203 | UpdateAllTreeViewItems(); 204 | _modelHandled = false; 205 | } 206 | 207 | /// 208 | protected override void OnDetaching() 209 | { 210 | base.OnDetaching(); 211 | 212 | if (AssociatedObject != null) 213 | { 214 | AssociatedObject.ItemContainerStyle?.Setters.Remove(_treeViewItemEventSetter); 215 | AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged; 216 | ((INotifyCollectionChanged) AssociatedObject.Items).CollectionChanged -= OnTreeViewItemsChanged; 217 | } 218 | } 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/ArrayToStringConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Globalization; 4 | using System.Linq; 5 | using System.Windows.Data; 6 | 7 | namespace Tyrrrz.WpfExtensions.Converters 8 | { 9 | /// 10 | /// Converts to by using 11 | /// 12 | [ValueConversion(typeof(IEnumerable), typeof(string))] 13 | public class ArrayToStringConverter : IValueConverter 14 | { 15 | /// 16 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 17 | { 18 | if (value == null) return null; 19 | 20 | var enumerable = (IEnumerable) value; 21 | var separator = parameter as string ?? ", "; 22 | return string.Join(separator, enumerable.Cast()); 23 | } 24 | 25 | /// 26 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 27 | { 28 | if (value == null) return null; 29 | 30 | var joined = (string) value; 31 | var separator = parameter as string ?? ", "; 32 | return joined.Split(new [] {separator}, StringSplitOptions.RemoveEmptyEntries); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/BoolAndMultiConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Windows.Data; 5 | 6 | namespace Tyrrrz.WpfExtensions.Converters 7 | { 8 | /// 9 | /// Converts multiple bools into one by using AND 10 | /// 11 | public class BoolAndMultiConverter : IMultiValueConverter 12 | { 13 | /// 14 | public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | return values.Cast().All(b => b); 17 | } 18 | 19 | /// 20 | public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) 21 | { 22 | throw new NotImplementedException(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/BoolOrMultiConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Windows.Data; 5 | 6 | namespace Tyrrrz.WpfExtensions.Converters 7 | { 8 | /// 9 | /// Converts multiple bools into one by using OR 10 | /// 11 | public class BoolOrMultiConverter : IMultiValueConverter 12 | { 13 | /// 14 | public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | return values.Cast().Any(b => b); 17 | } 18 | 19 | /// 20 | public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) 21 | { 22 | throw new NotImplementedException(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/BoolToVisibilityConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows; 4 | using System.Windows.Data; 5 | 6 | namespace Tyrrrz.WpfExtensions.Converters 7 | { 8 | /// 9 | /// Converts bool to visibility 10 | /// 11 | [ValueConversion(typeof(bool), typeof(Visibility))] 12 | public class BoolToVisibilityConverter : IValueConverter 13 | { 14 | /// 15 | public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture) 16 | { 17 | if (value == null) 18 | throw new ArgumentNullException(nameof(value)); 19 | 20 | var visibility = Visibility.Hidden; 21 | var flag = (bool) value; 22 | 23 | // Set default visibility if parameter is set 24 | if (parameter is Visibility) 25 | visibility = (Visibility) parameter; 26 | 27 | return flag ? Visibility.Visible : visibility; 28 | } 29 | 30 | /// 31 | public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 32 | { 33 | if (value == null) 34 | throw new ArgumentNullException(nameof(value)); 35 | 36 | var visibility = (Visibility) value; 37 | return visibility == Visibility.Visible; 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/BoolXorMultiConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Windows.Data; 5 | 6 | namespace Tyrrrz.WpfExtensions.Converters 7 | { 8 | /// 9 | /// Converts multiple bools into one by using XOR 10 | /// 11 | public class BoolXorMultiConverter : IMultiValueConverter 12 | { 13 | /// 14 | public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | return values.Cast().Select(System.Convert.ToInt32).Sum() == 1; 17 | } 18 | 19 | /// 20 | public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) 21 | { 22 | throw new NotImplementedException(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/ByteArrayToImageConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.IO; 4 | using System.Windows.Data; 5 | using System.Windows.Media; 6 | using System.Windows.Media.Imaging; 7 | 8 | namespace Tyrrrz.WpfExtensions.Converters 9 | { 10 | /// 11 | /// Converts byte array to imaage 12 | /// 13 | [ValueConversion(typeof(byte[]), typeof(ImageSource))] 14 | public class ByteArrayToImageConverter : IValueConverter 15 | { 16 | /// 17 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 18 | { 19 | if (value == null) return null; 20 | 21 | var bytes = (byte[]) value; 22 | var image = new BitmapImage(); 23 | if (bytes.Length == 0) return image; 24 | 25 | using (var mem = new MemoryStream(bytes)) 26 | { 27 | mem.Position = 0; 28 | image.BeginInit(); 29 | image.CreateOptions = BitmapCreateOptions.PreservePixelFormat; 30 | image.CacheOption = BitmapCacheOption.OnLoad; 31 | image.UriSource = null; 32 | image.StreamSource = mem; 33 | image.EndInit(); 34 | } 35 | image.Freeze(); 36 | return image; 37 | } 38 | 39 | /// 40 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 41 | { 42 | throw new NotImplementedException(); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/ByteArrayToStringConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Text; 4 | using System.Windows.Data; 5 | 6 | namespace Tyrrrz.WpfExtensions.Converters 7 | { 8 | /// 9 | /// Converts byte array to string 10 | /// 11 | [ValueConversion(typeof(byte[]), typeof(string))] 12 | public class ByteArrayToStringConverter : IValueConverter 13 | { 14 | /// 15 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 16 | { 17 | if (value == null) return null; 18 | 19 | var bytes = (byte[]) value; 20 | var encoding = parameter as Encoding ?? Encoding.UTF8; 21 | return encoding.GetString(bytes); 22 | } 23 | 24 | /// 25 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 26 | { 27 | if (value == null) return null; 28 | 29 | var str = (string) value; 30 | var encoding = parameter as Encoding ?? Encoding.UTF8; 31 | return encoding.GetBytes(str); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/ColorToBrushConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | using System.Windows.Media; 5 | 6 | namespace Tyrrrz.WpfExtensions.Converters 7 | { 8 | /// 9 | /// Converts color to solid color brush 10 | /// 11 | [ValueConversion(typeof (Color), typeof (Brush))] 12 | public class ColorToBrushConverter : IValueConverter 13 | { 14 | /// 15 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 16 | { 17 | if (value == null) 18 | throw new ArgumentNullException(nameof(value)); 19 | 20 | var color = (Color) value; 21 | return new SolidColorBrush(color); 22 | } 23 | 24 | /// 25 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 26 | { 27 | if (value == null) 28 | throw new ArgumentNullException(nameof(value)); 29 | 30 | var c = (SolidColorBrush) value; 31 | return c.Color; 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/EnumToStringConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Text.RegularExpressions; 4 | using System.Windows.Data; 5 | 6 | namespace Tyrrrz.WpfExtensions.Converters 7 | { 8 | /// 9 | /// Converts an enum value to 10 | /// 11 | [ValueConversion(typeof(Enum), typeof(string))] 12 | public class EnumToStringConverter : IValueConverter 13 | { 14 | /// 15 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 16 | { 17 | if (value == null) 18 | throw new ArgumentNullException(nameof(value)); 19 | 20 | var e = (Enum) value; 21 | var str = e.ToString(); 22 | return Regex.Replace(str, @"([a-z])([A-Z])", "$1 $2"); 23 | } 24 | 25 | /// 26 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 27 | { 28 | if (value == null) 29 | throw new ArgumentNullException(nameof(value)); 30 | 31 | var str = (string) value; 32 | str = str.Replace(" ", ""); 33 | return Enum.Parse(targetType, str, true); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/InvertBoolConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | 5 | namespace Tyrrrz.WpfExtensions.Converters 6 | { 7 | /// 8 | /// Converts bool to inverted bool value 9 | /// 10 | [ValueConversion(typeof (bool), typeof (bool))] 11 | public class InvertBoolConverter : IValueConverter 12 | { 13 | /// 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | if (value == null) 17 | throw new ArgumentNullException(nameof(value)); 18 | 19 | var flag = (bool) value; 20 | return !flag; 21 | } 22 | 23 | /// 24 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 25 | { 26 | if (value == null) 27 | throw new ArgumentNullException(nameof(value)); 28 | 29 | var flag = (bool) value; 30 | return !flag; 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/InvertBoolToVisibilityConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows; 4 | using System.Windows.Data; 5 | 6 | namespace Tyrrrz.WpfExtensions.Converters 7 | { 8 | /// 9 | /// Converts bool to inverted value to visibility 10 | /// 11 | [ValueConversion(typeof (bool), typeof (Visibility))] 12 | public class InvertBoolToVisibilityConverter : BoolToVisibilityConverter 13 | { 14 | /// 15 | public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) 16 | { 17 | if (value == null) 18 | throw new ArgumentNullException(nameof(value)); 19 | 20 | var flag = (bool) value; 21 | // ReSharper disable once PossibleNullReferenceException 22 | return (Visibility) base.Convert(!flag, targetType, parameter, culture); 23 | } 24 | 25 | /// 26 | public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 27 | { 28 | if (value == null) 29 | throw new ArgumentNullException(nameof(value)); 30 | 31 | // ReSharper disable once PossibleNullReferenceException 32 | var flag = (bool) base.ConvertBack(value, targetType, parameter, culture); 33 | return !flag; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/TimeSpanToDaysConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | 5 | namespace Tyrrrz.WpfExtensions.Converters 6 | { 7 | /// 8 | /// Converts timespan to days 9 | /// 10 | [ValueConversion(typeof(TimeSpan), typeof(double))] 11 | public class TimeSpanToDaysConverter : IValueConverter 12 | { 13 | /// 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | if (value == null) 17 | throw new ArgumentNullException(nameof(value)); 18 | 19 | var ts = (TimeSpan) value; 20 | return ts.TotalDays; 21 | } 22 | 23 | /// 24 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 25 | { 26 | if (value == null) 27 | throw new ArgumentNullException(nameof(value)); 28 | 29 | var ticks = (double) value; 30 | return TimeSpan.FromDays(ticks); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/TimeSpanToHoursConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | 5 | namespace Tyrrrz.WpfExtensions.Converters 6 | { 7 | /// 8 | /// Converts timespan to hours 9 | /// 10 | [ValueConversion(typeof(TimeSpan), typeof(double))] 11 | public class TimeSpanToHoursConverter : IValueConverter 12 | { 13 | /// 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | if (value == null) 17 | throw new ArgumentNullException(nameof(value)); 18 | 19 | var ts = (TimeSpan) value; 20 | return ts.TotalHours; 21 | } 22 | 23 | /// 24 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 25 | { 26 | if (value == null) 27 | throw new ArgumentNullException(nameof(value)); 28 | 29 | var ticks = (double) value; 30 | return TimeSpan.FromHours(ticks); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/TimeSpanToMillisecondsConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | 5 | namespace Tyrrrz.WpfExtensions.Converters 6 | { 7 | /// 8 | /// Converts timespan to milliseconds 9 | /// 10 | [ValueConversion(typeof(TimeSpan), typeof(double))] 11 | public class TimeSpanToMillisecondsConverter : IValueConverter 12 | { 13 | /// 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | if (value == null) 17 | throw new ArgumentNullException(nameof(value)); 18 | 19 | var ts = (TimeSpan) value; 20 | return ts.TotalMilliseconds; 21 | } 22 | 23 | /// 24 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 25 | { 26 | if (value == null) 27 | throw new ArgumentNullException(nameof(value)); 28 | 29 | var ticks = (double) value; 30 | return TimeSpan.FromMilliseconds(ticks); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/TimeSpanToMinutesConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | 5 | namespace Tyrrrz.WpfExtensions.Converters 6 | { 7 | /// 8 | /// Converts timespan to minutes 9 | /// 10 | [ValueConversion(typeof(TimeSpan), typeof(double))] 11 | public class TimeSpanToMinutesConverter : IValueConverter 12 | { 13 | /// 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | if (value == null) 17 | throw new ArgumentNullException(nameof(value)); 18 | 19 | var ts = (TimeSpan) value; 20 | return ts.TotalMinutes; 21 | } 22 | 23 | /// 24 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 25 | { 26 | if (value == null) 27 | throw new ArgumentNullException(nameof(value)); 28 | 29 | var ticks = (double) value; 30 | return TimeSpan.FromMinutes(ticks); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Converters/TimeSpanToSecondsConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | 5 | namespace Tyrrrz.WpfExtensions.Converters 6 | { 7 | /// 8 | /// Converts timespan to seconds 9 | /// 10 | [ValueConversion(typeof(TimeSpan), typeof(double))] 11 | public class TimeSpanToSecondsConverter : IValueConverter 12 | { 13 | /// 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | if (value == null) 17 | throw new ArgumentNullException(nameof(value)); 18 | 19 | var ts = (TimeSpan) value; 20 | return ts.TotalSeconds; 21 | } 22 | 23 | /// 24 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 25 | { 26 | if (value == null) 27 | throw new ArgumentNullException(nameof(value)); 28 | 29 | var ticks = (double) value; 30 | return TimeSpan.FromSeconds(ticks); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/ConvertersDictionary.xaml: -------------------------------------------------------------------------------- 1 |  4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Types/WatermarkAdorner.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | using System.Windows.Controls; 3 | using System.Windows.Data; 4 | using System.Windows.Documents; 5 | using System.Windows.Media; 6 | 7 | namespace Tyrrrz.WpfExtensions.Types 8 | { 9 | /// 10 | /// Adorner for the watermark 11 | /// 12 | public class WatermarkAdorner : Adorner 13 | { 14 | /// 15 | /// Gets the control that is being adorned 16 | /// 17 | private Control Control => (Control) AdornedElement; 18 | 19 | /// 20 | /// that holds the watermark 21 | /// 22 | private ContentPresenter Presenter { get; } 23 | 24 | /// 25 | /// Gets the number of children for the . 26 | /// 27 | protected override int VisualChildrenCount => 1; 28 | 29 | /// 30 | /// Initializes a new instance of the class 31 | /// 32 | /// to be adorned 33 | /// The watermark 34 | public WatermarkAdorner(UIElement adornedElement, object watermark) : 35 | base(adornedElement) 36 | { 37 | IsHitTestVisible = false; 38 | 39 | Presenter = new ContentPresenter 40 | { 41 | Content = watermark, 42 | Opacity = 0.5, 43 | Margin = new Thickness(Control.Margin.Left + Control.Padding.Left, 44 | Control.Margin.Top + Control.Padding.Top, 0, 0) 45 | }; 46 | 47 | if (Control is ItemsControl && !(Control is ComboBox)) 48 | { 49 | Presenter.VerticalAlignment = VerticalAlignment.Center; 50 | Presenter.HorizontalAlignment = HorizontalAlignment.Center; 51 | } 52 | 53 | // Hide the control adorner when the adorned element is hidden 54 | var binding = new Binding(nameof(IsVisible)) 55 | { 56 | Source = adornedElement, 57 | Converter = new BooleanToVisibilityConverter() 58 | }; 59 | SetBinding(VisibilityProperty, binding); 60 | } 61 | 62 | /// 63 | /// Returns a specified child for the parent . 64 | /// 65 | /// A 32-bit signed integer that represents the index value of the child . The value of index must be between 0 and - 1. 66 | /// The child . 67 | protected override Visual GetVisualChild(int index) 68 | { 69 | return Presenter; 70 | } 71 | 72 | /// 73 | /// Implements any custom measuring behavior for the adorner. 74 | /// 75 | /// A size to constrain the adorner to. 76 | /// A object representing the amount of layout space needed by the adorner. 77 | protected override Size MeasureOverride(Size constraint) 78 | { 79 | // Here's the secret to getting the adorner to cover the whole control 80 | Presenter.Measure(Control.RenderSize); 81 | return Control.RenderSize; 82 | } 83 | 84 | /// 85 | /// When overridden in a derived class, positions child elements and determines a size for a derived class. 86 | /// 87 | /// The final area within the parent that this element should use to arrange itself and its children. 88 | /// The actual size used. 89 | protected override Size ArrangeOverride(Size finalSize) 90 | { 91 | Presenter.Arrange(new Rect(finalSize)); 92 | return finalSize; 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/Tyrrrz.WpfExtensions.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net45 5 | 1.0.5 6 | Tyrrrz 7 | $(Company) 8 | Copyright (C) Alexey Golub 9 | WPF extensions for rapid development 10 | https://github.com/Tyrrrz/WpfExtensions 11 | MIT 12 | False 13 | True 14 | bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Tyrrrz.WpfExtensions/WpfExt.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using System.Windows; 4 | using System.Windows.Threading; 5 | 6 | namespace Tyrrrz.WpfExtensions 7 | { 8 | /// 9 | /// WPF extension methods for rapid development 10 | /// 11 | public static class WpfExt 12 | { 13 | /// 14 | /// Invokes the delegate on the dispatcher thread if necessary 15 | /// 16 | public static void InvokeSafe(this Dispatcher dispatcher, Action action) 17 | { 18 | if (dispatcher.CheckAccess()) 19 | action(); 20 | else 21 | dispatcher.Invoke(action); 22 | } 23 | 24 | /// 25 | /// Invokes the delegate on the dispatcher thread if necessary 26 | /// 27 | public static T InvokeSafe(this Dispatcher dispatcher, Func func) 28 | { 29 | if (dispatcher.CheckAccess()) 30 | return func(); 31 | return dispatcher.Invoke(func); 32 | } 33 | 34 | /// 35 | /// Invokes the delegate asynchronously on the dispatcher thread if necessary or synchronously if not 36 | /// 37 | public static async Task InvokeSafeAsync(this Dispatcher dispatcher, Action action) 38 | { 39 | if (dispatcher.CheckAccess()) 40 | action(); 41 | else 42 | await dispatcher.InvokeAsync(action); 43 | } 44 | 45 | /// 46 | /// Invokes the delegate asynchronously on the dispatcher thread if necessary or synchronously if not 47 | /// 48 | public static async Task InvokeSafeAsync(this Dispatcher dispatcher, Func func) 49 | { 50 | if (dispatcher.CheckAccess()) 51 | return func(); 52 | return await dispatcher.InvokeAsync(func); 53 | } 54 | 55 | /// 56 | /// Safely shutdowns an application from dispatcher thread 57 | /// 58 | public static void ShutdownSafe(this Application application, int code) 59 | { 60 | InvokeSafe(application.Dispatcher, () => application.Shutdown(code)); 61 | } 62 | 63 | /// 64 | /// Safely shutdowns an application from dispatcher thread 65 | /// 66 | public static void ShutdownSafe(this Application application, Enum code) 67 | { 68 | var codeActualValue = Convert.ChangeType(code, code.GetTypeCode()); 69 | var codeInt = (int?) codeActualValue ?? 0; 70 | InvokeSafe(application.Dispatcher, () => application.Shutdown(codeInt)); 71 | } 72 | 73 | /// 74 | /// Safely shutdowns an application from dispatcher thread 75 | /// 76 | public static void ShutdownSafe(this Application application) 77 | { 78 | InvokeSafe(application.Dispatcher, application.Shutdown); 79 | } 80 | 81 | /// 82 | /// Shows a message box safely from the dispatcher of the given window 83 | /// 84 | public static MessageBoxResult ShowMessage(this Window window, 85 | string title = null, string message = null, 86 | MessageBoxButton buttonSet = MessageBoxButton.OK, MessageBoxImage image = MessageBoxImage.None, 87 | MessageBoxResult defaultResult = default(MessageBoxResult)) 88 | { 89 | var func = 90 | new Func(() => MessageBox.Show(window, message, title, buttonSet, image, defaultResult)); 91 | return InvokeSafe(window.Dispatcher, func); 92 | } 93 | 94 | /// 95 | /// Shows a message box asynchronously from the dispatcher of the given window 96 | /// 97 | public static async Task ShowMessageAsync(this Window window, 98 | string title = null, string message = null, 99 | MessageBoxButton buttonSet = MessageBoxButton.OK, MessageBoxImage image = MessageBoxImage.None, 100 | MessageBoxResult defaultResult = default(MessageBoxResult)) 101 | { 102 | var func = 103 | new Func(() => MessageBox.Show(window, message, title, buttonSet, image, defaultResult)); 104 | return await InvokeSafeAsync(window.Dispatcher, func); 105 | } 106 | } 107 | } -------------------------------------------------------------------------------- /WpfExtensions.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26730.12 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{07DCAECA-F534-412B-AAE2-153BEB288C13}" 7 | ProjectSection(SolutionItems) = preProject 8 | License.txt = License.txt 9 | Readme.md = Readme.md 10 | EndProjectSection 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tyrrrz.WpfExtensions", "Tyrrrz.WpfExtensions\Tyrrrz.WpfExtensions.csproj", "{9B309BC5-C296-43C1-AB54-0B83978023B5}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tyrrrz.WpfExtensions.Tests", "Tyrrrz.WpfExtensions.Tests\Tyrrrz.WpfExtensions.Tests.csproj", "{490F8FB7-82F4-489C-9F1E-73BB303074B7}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {9B309BC5-C296-43C1-AB54-0B83978023B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {9B309BC5-C296-43C1-AB54-0B83978023B5}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {9B309BC5-C296-43C1-AB54-0B83978023B5}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {9B309BC5-C296-43C1-AB54-0B83978023B5}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {490F8FB7-82F4-489C-9F1E-73BB303074B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {490F8FB7-82F4-489C-9F1E-73BB303074B7}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {490F8FB7-82F4-489C-9F1E-73BB303074B7}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {490F8FB7-82F4-489C-9F1E-73BB303074B7}.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 = {1EFFFBD9-8212-44D5-8050-9976443C3828} 36 | EndGlobalSection 37 | EndGlobal 38 | --------------------------------------------------------------------------------