Browse Source

Merge branch 'v2_develop' into copilot/fix-3ee850b1-eb6b-46b0-964b-3b98d2c0c14e

Tig 2 weeks ago
parent
commit
862ccec542
100 changed files with 4817 additions and 5796 deletions
  1. 79 0
      .github/workflows/README.md
  2. 74 28
      .github/workflows/unit-tests.yml
  3. 1 0
      .gitignore
  4. 21 153
      CONTRIBUTING.md
  5. 1 1
      Directory.Packages.props
  6. 0 2
      Examples/CommunityToolkitExample/LoginView.cs
  7. 4 4
      Examples/CommunityToolkitExample/LoginViewModel.cs
  8. 0 1
      Examples/CommunityToolkitExample/Message.cs
  9. 7 8
      Examples/CommunityToolkitExample/Program.cs
  10. 25 21
      Examples/CommunityToolkitExample/README.md
  11. 27 36
      Examples/Example/Example.cs
  12. 1 4
      Examples/Example/README.md
  13. 11 0
      Examples/FluentExample/FluentExample.csproj
  14. 109 0
      Examples/FluentExample/Program.cs
  15. 2 2
      Examples/NativeAot/Program.cs
  16. 7 8
      Examples/ReactiveExample/Program.cs
  17. 8 4
      Examples/ReactiveExample/README.md
  18. 28 21
      Examples/ReactiveExample/TerminalScheduler.cs
  19. 1 2
      Examples/ReactiveExample/ViewExtensions.cs
  20. 168 0
      Examples/RunnableWrapperExample/Program.cs
  21. 15 0
      Examples/RunnableWrapperExample/RunnableWrapperExample.csproj
  22. 15 15
      Examples/SelfContained/Program.cs
  23. 26 0
      Examples/SelfContained/README.md
  24. 1 1
      Examples/UICatalog/README.md
  25. 4 4
      Examples/UICatalog/Resources/config.json
  26. 7 5
      Examples/UICatalog/Scenario.cs
  27. 8 8
      Examples/UICatalog/Scenarios/Adornments.cs
  28. 8 1
      Examples/UICatalog/Scenarios/AllViewsTester.cs
  29. 1 1
      Examples/UICatalog/Scenarios/AnimationScenario/AnimationScenario.cs
  30. 4 4
      Examples/UICatalog/Scenarios/Arrangement.cs
  31. 20 20
      Examples/UICatalog/Scenarios/Bars.cs
  32. 5 5
      Examples/UICatalog/Scenarios/Buttons.cs
  33. 5 5
      Examples/UICatalog/Scenarios/CharacterMap/CharacterMap.cs
  34. 3 2
      Examples/UICatalog/Scenarios/ChineseUI.cs
  35. 210 188
      Examples/UICatalog/Scenarios/ClassExplorer.cs
  36. 1 1
      Examples/UICatalog/Scenarios/Clipping.cs
  37. 169 112
      Examples/UICatalog/Scenarios/CollectionNavigatorTester.cs
  38. 28 1
      Examples/UICatalog/Scenarios/ColorPicker.cs
  39. 15 4
      Examples/UICatalog/Scenarios/CombiningMarks.cs
  40. 1 1
      Examples/UICatalog/Scenarios/ComboBoxIteration.cs
  41. 1 1
      Examples/UICatalog/Scenarios/ComputedLayout.cs
  42. 5 5
      Examples/UICatalog/Scenarios/ConfigurationEditor.cs
  43. 23 19
      Examples/UICatalog/Scenarios/ContextMenus.cs
  44. 270 211
      Examples/UICatalog/Scenarios/CsvEditor.cs
  45. 8 2
      Examples/UICatalog/Scenarios/Dialogs.cs
  46. 0 1413
      Examples/UICatalog/Scenarios/DynamicMenuBar.cs
  47. 6 6
      Examples/UICatalog/Scenarios/DynamicStatusBar.cs
  48. 504 677
      Examples/UICatalog/Scenarios/Editor.cs
  49. 39 17
      Examples/UICatalog/Scenarios/EditorsAndHelpers/AllViewsView.cs
  50. 1 1
      Examples/UICatalog/Scenarios/EditorsAndHelpers/ArrangementEditor.cs
  51. 1 1
      Examples/UICatalog/Scenarios/EditorsAndHelpers/DimEditor.cs
  52. 1 1
      Examples/UICatalog/Scenarios/EditorsAndHelpers/PosEditor.cs
  53. 6 6
      Examples/UICatalog/Scenarios/FileDialogExamples.cs
  54. 1 1
      Examples/UICatalog/Scenarios/Generic.cs
  55. 298 338
      Examples/UICatalog/Scenarios/GraphViewExample.cs
  56. 9 9
      Examples/UICatalog/Scenarios/HexEditor.cs
  57. 3 3
      Examples/UICatalog/Scenarios/Images.cs
  58. 71 43
      Examples/UICatalog/Scenarios/InteractiveTree.cs
  59. 4 4
      Examples/UICatalog/Scenarios/KeyBindings.cs
  60. 4 4
      Examples/UICatalog/Scenarios/Keys.cs
  61. 1 1
      Examples/UICatalog/Scenarios/LineCanvasExperiment.cs
  62. 1 1
      Examples/UICatalog/Scenarios/LineDrawing.cs
  63. 309 268
      Examples/UICatalog/Scenarios/ListColumns.cs
  64. 1 1
      Examples/UICatalog/Scenarios/ListViewWithSelection.cs
  65. 2 2
      Examples/UICatalog/Scenarios/ListsAndCombos.cs
  66. 92 77
      Examples/UICatalog/Scenarios/Localization.cs
  67. 7 7
      Examples/UICatalog/Scenarios/Mazing.cs
  68. 0 135
      Examples/UICatalog/Scenarios/MenuBarScenario.cs
  69. 5 5
      Examples/UICatalog/Scenarios/Menus.cs
  70. 9 9
      Examples/UICatalog/Scenarios/MessageBoxes.cs
  71. 2 2
      Examples/UICatalog/Scenarios/Mouse.cs
  72. 82 73
      Examples/UICatalog/Scenarios/MultiColouredTable.cs
  73. 4 4
      Examples/UICatalog/Scenarios/Navigation.cs
  74. 154 108
      Examples/UICatalog/Scenarios/Notepad.cs
  75. 1 1
      Examples/UICatalog/Scenarios/PosAlignDemo.cs
  76. 14 10
      Examples/UICatalog/Scenarios/ProgressBarStyles.cs
  77. 4 4
      Examples/UICatalog/Scenarios/RunTExample.cs
  78. 177 74
      Examples/UICatalog/Scenarios/RuneWidthGreaterThanOne.cs
  79. 15 15
      Examples/UICatalog/Scenarios/Scrolling.cs
  80. 31 31
      Examples/UICatalog/Scenarios/Shortcuts.cs
  81. 126 117
      Examples/UICatalog/Scenarios/SingleBackgroundWorker.cs
  82. 9 9
      Examples/UICatalog/Scenarios/Sliders.cs
  83. 17 17
      Examples/UICatalog/Scenarios/SpinnerStyles.cs
  84. 58 65
      Examples/UICatalog/Scenarios/SyntaxHighlighting.cs
  85. 151 102
      Examples/UICatalog/Scenarios/TabViewExample.cs
  86. 327 451
      Examples/UICatalog/Scenarios/TableEditor.cs
  87. 3 6
      Examples/UICatalog/Scenarios/TextEffectsScenario.cs
  88. 1 1
      Examples/UICatalog/Scenarios/TextFormatterDemo.cs
  89. 1 1
      Examples/UICatalog/Scenarios/TextStyles.cs
  90. 187 94
      Examples/UICatalog/Scenarios/TextViewAutocompletePopup.cs
  91. 1 1
      Examples/UICatalog/Scenarios/Themes.cs
  92. 4 4
      Examples/UICatalog/Scenarios/Threading.cs
  93. 2 2
      Examples/UICatalog/Scenarios/Transparent.cs
  94. 123 81
      Examples/UICatalog/Scenarios/TreeUseCases.cs
  95. 340 249
      Examples/UICatalog/Scenarios/TreeViewFileSystem.cs
  96. 0 157
      Examples/UICatalog/Scenarios/TrueColors.cs
  97. 96 94
      Examples/UICatalog/Scenarios/Unicode.cs
  98. 3 3
      Examples/UICatalog/Scenarios/ViewportSettings.cs
  99. 4 4
      Examples/UICatalog/Scenarios/WindowsAndFrameViews.cs
  100. 78 75
      Examples/UICatalog/Scenarios/WizardAsView.cs

+ 79 - 0
.github/workflows/README.md

@@ -0,0 +1,79 @@
+## CI/CD Workflows
+
+The repository uses multiple GitHub Actions workflows. What runs and when:
+
+### 1) Build Solution (`.github/workflows/build.yml`)
+
+- **Triggers**: push and pull_request to `v2_release`, `v2_develop` (ignores `**.md`); supports `workflow_call`
+- **Runner/timeout**: `ubuntu-latest`, 10 minutes
+- **Steps**:
+- Checkout and setup .NET 8.x GA
+- `dotnet restore`
+- Build Debug: `dotnet build --configuration Debug --no-restore -property:NoWarn=0618%3B0612`
+- Build Release (library): `dotnet build Terminal.Gui/Terminal.Gui.csproj --configuration Release --no-incremental --force -property:NoWarn=0618%3B0612`
+- Pack Release: `dotnet pack Terminal.Gui/Terminal.Gui.csproj --configuration Release --output ./local_packages -property:NoWarn=0618%3B0612`
+- Restore NativeAot/SelfContained examples, then restore solution again
+- Build Release for `Examples/NativeAot` and `Examples/SelfContained`
+- Build Release solution
+- Upload artifacts named `build-artifacts`, retention 1 day
+
+### 2) Build & Run Unit Tests (`.github/workflows/unit-tests.yml`)
+
+- **Triggers**: push and pull_request to `v2_release`, `v2_develop` (ignores `**.md`)
+- **Matrix**: Ubuntu/Windows/macOS
+- **Timeout**: 15 minutes per job
+- **Process**:
+1. Calls build workflow to build solution once
+2. Downloads build artifacts
+3. Runs `dotnet restore` (required for `--no-build` to work)
+4. **Performance optimizations**:
+   - Disables Windows Defender on Windows runners (significant speedup)
+   - Collects code coverage **only on Linux** (ubuntu-latest) for performance
+   - Windows and macOS skip coverage collection to reduce test time
+   - Increased blame-hang-timeout to 120s for Windows/macOS (60s for Linux)
+5. Runs two test jobs:
+   - **Non-parallel UnitTests**: `Tests/UnitTests` with blame/diag flags; `xunit.stopOnFail=false`
+   - **Parallel UnitTestsParallelizable**: `Tests/UnitTestsParallelizable` with blame/diag flags; `xunit.stopOnFail=false`
+6. Uploads test logs and diagnostic data from all runners
+7. **Uploads code coverage to Codecov only from Linux runner**
+
+**Test results**: All tests output to unified `TestResults/` directory at repository root
+
+### 3) Build & Run Integration Tests (`.github/workflows/integration-tests.yml`)
+
+- **Triggers**: push and pull_request to `v2_release`, `v2_develop` (ignores `**.md`)
+- **Matrix**: Ubuntu/Windows/macOS
+- **Timeout**: 15 minutes
+- **Process**:
+1. Calls build workflow
+2. Downloads build artifacts
+3. Runs `dotnet restore`
+4. **Performance optimizations** (same as unit tests):
+   - Disables Windows Defender on Windows runners
+   - Collects code coverage **only on Linux**
+   - Increased blame-hang-timeout to 120s for Windows/macOS
+5. Runs IntegrationTests with blame/diag flags; `xunit.stopOnFail=true`
+6. Uploads logs per-OS
+7. **Uploads coverage to Codecov only from Linux runner**
+
+### 4) Publish to NuGet (`.github/workflows/publish.yml`)
+
+- **Triggers**: push to `v2_release`, `v2_develop`, and tags `v*`(ignores `**.md`)
+- Uses GitVersion to compute SemVer, builds Release, packs with symbols, and pushes to NuGet.org using `NUGET_API_KEY`
+
+### 5) Build and publish API docs (`.github/workflows/api-docs.yml`)
+
+- **Triggers**: push to `v1_release` and `v2_develop`
+- Builds DocFX site on Windows and deploys to GitHub Pages when `ref_name` is `v2_release` or `v2_develop`
+
+
+### Replicating CI Locally
+
+```bash
+# Full CI sequence:
+dotnet restore
+dotnet build --configuration Debug --no-restore
+dotnet test Tests/UnitTests --no-build --verbosity normal
+dotnet test Tests/UnitTestsParallelizable --no-build --verbosity normal
+dotnet build --configuration Release --no-restore
+```

+ 74 - 28
.github/workflows/unit-tests.yml

@@ -120,7 +120,7 @@ jobs:
       matrix:
       matrix:
         os: [ ubuntu-latest, windows-latest, macos-latest ]
         os: [ ubuntu-latest, windows-latest, macos-latest ]
 
 
-    timeout-minutes: 15
+    timeout-minutes: 60
     steps:
     steps:
 
 
     - name: Checkout code
     - name: Checkout code
@@ -154,35 +154,81 @@ jobs:
       shell: bash
       shell: bash
       run: echo "VSTEST_DUMP_PATH=logs/UnitTestsParallelizable/${{ runner.os }}/" >> $GITHUB_ENV
       run: echo "VSTEST_DUMP_PATH=logs/UnitTestsParallelizable/${{ runner.os }}/" >> $GITHUB_ENV
 
 
-    - name: Run UnitTestsParallelizable
+    - name: Run UnitTestsParallelizable (10 iterations with varying parallelization)
       shell: bash
       shell: bash
       run: |
       run: |
-        if [ "${{ runner.os }}" == "Linux" ]; then
-          # Run with coverage on Linux only
-          dotnet test Tests/UnitTestsParallelizable \
-            --no-build \
-            --verbosity normal \
-            --collect:"XPlat Code Coverage" \
-            --settings Tests/UnitTests/runsettings.coverage.xml \
-            --diag:logs/UnitTestsParallelizable/${{ runner.os }}/logs.txt \
-            --blame \
-            --blame-crash \
-            --blame-hang \
-            --blame-hang-timeout 60s \
-            --blame-crash-collect-always
-        else
-          # Run without coverage on Windows/macOS for speed
-          dotnet test Tests/UnitTestsParallelizable \
-            --no-build \
-            --verbosity normal \
-            --settings Tests/UnitTestsParallelizable/runsettings.xml \
-            --diag:logs/UnitTestsParallelizable/${{ runner.os }}/logs.txt \
-            --blame \
-            --blame-crash \
-            --blame-hang \
-            --blame-hang-timeout 60s \
-            --blame-crash-collect-always
-        fi
+        # Run tests 3 times with different parallelization settings to expose concurrency issues
+        for RUN in {1..3}; do
+          echo "============================================"
+          echo "Starting test run $RUN of 3"
+          echo "============================================"
+          
+          # Use a combination of run number and timestamp to create different execution patterns
+          SEED=$((1000 + $RUN + $(date +%s) % 1000))
+          echo "Using randomization seed: $SEED"
+          
+          # Vary the xUnit parallelization based on run number to expose race conditions
+          # Runs 1-3: Default parallelization (2x CPU cores)
+          # Runs 4-6: Max parallelization (unlimited)
+          # Runs 7-9: Single threaded (1)
+          # Run 10: Random (1-4 threads)
+          if [ $RUN -le 3 ]; then
+            XUNIT_MAX_PARALLEL_THREADS="2x"
+            echo "Run $RUN: Using default parallelization (2x)"
+          elif [ $RUN -le 6 ]; then
+            XUNIT_MAX_PARALLEL_THREADS="unlimited"
+            echo "Run $RUN: Using maximum parallelization (unlimited)"
+          elif [ $RUN -le 9 ]; then
+            XUNIT_MAX_PARALLEL_THREADS="1"
+            echo "Run $RUN: Using single-threaded execution"
+          else
+            # Random parallelization based on seed
+            PROC_COUNT=$(( ($SEED % 4) + 1 ))
+            XUNIT_MAX_PARALLEL_THREADS="$PROC_COUNT"
+            echo "Run $RUN: Using random parallelization with $PROC_COUNT threads"
+          fi
+          
+          # Run tests with or without coverage based on OS and run number
+          if [ "${{ runner.os }}" == "Linux" ] && [ $RUN -eq 1 ]; then
+            echo "Run $RUN: Running with coverage collection"
+            dotnet test Tests/UnitTestsParallelizable \
+              --no-build \
+              --verbosity normal \
+              --collect:"XPlat Code Coverage" \
+              --settings Tests/UnitTests/runsettings.coverage.xml \
+              --diag:logs/UnitTestsParallelizable/${{ runner.os }}/run${RUN}-logs.txt \
+              --blame \
+              --blame-crash \
+              --blame-hang \
+              --blame-hang-timeout 60s \
+              --blame-crash-collect-always \
+              -- xUnit.MaxParallelThreads=${XUNIT_MAX_PARALLEL_THREADS}
+          else
+            dotnet test Tests/UnitTestsParallelizable \
+              --no-build \
+              --verbosity normal \
+              --settings Tests/UnitTestsParallelizable/runsettings.xml \
+              --diag:logs/UnitTestsParallelizable/${{ runner.os }}/run${RUN}-logs.txt \
+              --blame \
+              --blame-crash \
+              --blame-hang \
+              --blame-hang-timeout 60s \
+              --blame-crash-collect-always \
+              -- xUnit.MaxParallelThreads=${XUNIT_MAX_PARALLEL_THREADS}
+          fi
+          
+          if [ $? -ne 0 ]; then
+            echo "ERROR: Test run $RUN failed!"
+            exit 1
+          fi
+          
+          echo "Test run $RUN completed successfully"
+          echo ""
+        done
+        
+        echo "============================================"
+        echo "All 10 test runs completed successfully!"
+        echo "============================================"
 
 
     - name: Upload UnitTestsParallelizable Logs
     - name: Upload UnitTestsParallelizable Logs
       if: always()
       if: always()

+ 1 - 0
.gitignore

@@ -73,3 +73,4 @@ log.*
 !/Tests/coverage/.gitkeep   # keep folder in repo
 !/Tests/coverage/.gitkeep   # keep folder in repo
 /Tests/report/
 /Tests/report/
 *.cobertura.xml
 *.cobertura.xml
+/docfx/docs/migratingfromv1.md

+ 21 - 153
CONTRIBUTING.md

@@ -7,19 +7,16 @@ Welcome! This guide provides everything you need to know to contribute effective
 ## Table of Contents
 ## Table of Contents
 
 
 - [Project Overview](#project-overview)
 - [Project Overview](#project-overview)
-- [Building and Testing](#building-and-testing)
+- [Key Architecture Concepts](#key-architecture-concepts)
 - [Coding Conventions](#coding-conventions)
 - [Coding Conventions](#coding-conventions)
+- [Building and Testing](#building-and-testing)
 - [Testing Requirements](#testing-requirements)
 - [Testing Requirements](#testing-requirements)
 - [API Documentation Requirements](#api-documentation-requirements)
 - [API Documentation Requirements](#api-documentation-requirements)
 - [Pull Request Guidelines](#pull-request-guidelines)
 - [Pull Request Guidelines](#pull-request-guidelines)
 - [CI/CD Workflows](#cicd-workflows)
 - [CI/CD Workflows](#cicd-workflows)
 - [Repository Structure](#repository-structure)
 - [Repository Structure](#repository-structure)
 - [Branching Model](#branching-model)
 - [Branching Model](#branching-model)
-- [Key Architecture Concepts](#key-architecture-concepts)
 - [What NOT to Do](#what-not-to-do)
 - [What NOT to Do](#what-not-to-do)
-- [Additional Resources](#additional-resources)
-
----
 
 
 ## Project Overview
 ## Project Overview
 
 
@@ -32,8 +29,18 @@ Welcome! This guide provides everything you need to know to contribute effective
 - **Version**: v2 (Alpha), v1 (maintenance mode)
 - **Version**: v2 (Alpha), v1 (maintenance mode)
 - **Branching**: GitFlow model (v2_develop is default/active development)
 - **Branching**: GitFlow model (v2_develop is default/active development)
 
 
----
+## Key Architecture Concepts
+
+**⚠️ CRITICAL - AI Agents MUST understand these concepts before starting work.**
 
 
+- **Application Lifecycle** - How `Application.Init`, `Application.Run`, and `Application.Shutdown` work - [Application Deep Dive](./docfx/docs/application.md)
+- **Cancellable Workflow Patern** - [CWP Deep Dive](./docfx/docs/cancellable-work-pattern.md)
+- **View Hierarchy** - Understanding `View`, `Runnable`, `Window`, and view containment - [View Deep Dive](./docfx/docs/View.md)
+- **Layout System** - Pos, Dim, and automatic layout -  [Layout System](./docfx/docs/layout.md)
+- **Event System** - How keyboard, mouse, and application events flow - [Events Deep Dive](./docfx/docs/events.md)
+- **Driver Architecture** - How console drivers abstract platform differences - [Drivers](./docfx/docs/drivers.md)
+- **Drawing Model** - How rendering works with Attributes, Colors, and Glyphs  - [Drawing Deep Dive](./docfx/docs/drivers.md)
+ 
 ## Building and Testing
 ## Building and Testing
 
 
 ### Required Tools
 ### Required Tools
@@ -89,28 +96,18 @@ Welcome! This guide provides everything you need to know to contribute effective
 
 
 ### Common Build Issues
 ### Common Build Issues
 
 
-#### Issue: Build Warnings
-- **Expected**: None warnings (~100 currently).
-- **Action**: Don't add new warnings; fix warnings in code you modify
-
 #### Issue: NativeAot/SelfContained Build
 #### Issue: NativeAot/SelfContained Build
+
 - **Solution**: Restore these projects explicitly:
 - **Solution**: Restore these projects explicitly:
   ```bash
   ```bash
   dotnet restore ./Examples/NativeAot/NativeAot.csproj -f
   dotnet restore ./Examples/NativeAot/NativeAot.csproj -f
   dotnet restore ./Examples/SelfContained/SelfContained.csproj -f
   dotnet restore ./Examples/SelfContained/SelfContained.csproj -f
   ```
   ```
 
 
-### Running Examples
-
-**UICatalog** (comprehensive demo app):
-```bash
-dotnet run --project Examples/UICatalog/UICatalog.csproj
-```
-
----
-
 ## Coding Conventions
 ## Coding Conventions
 
 
+**⚠️ CRITICAL - These rules MUST be followed in ALL new or modified code**
+
 ### Code Style Tenets
 ### Code Style Tenets
 
 
 1. **Six-Year-Old Reading Level** - Readability over terseness
 1. **Six-Year-Old Reading Level** - Readability over terseness
@@ -161,8 +158,6 @@ dotnet run --project Examples/UICatalog/UICatalog.csproj
 
 
 **⚠️ CRITICAL - These conventions apply to ALL code - production code, test code, examples, and samples.**
 **⚠️ CRITICAL - These conventions apply to ALL code - production code, test code, examples, and samples.**
 
 
----
-
 ## Testing Requirements
 ## Testing Requirements
 
 
 ### Code Coverage
 ### Code Coverage
@@ -178,19 +173,17 @@ dotnet run --project Examples/UICatalog/UICatalog.csproj
 
 
 ### Test Patterns
 ### Test Patterns
 
 
-- **Parallelizable tests preferred** - Add new tests to `UnitTestsParallelizable` when possible
-- **Avoid static dependencies** - Don't use `Application.Init`, `ConfigurationManager` in tests
-- **Don't use `[AutoInitShutdown]`** - Legacy pattern, being phased out
 - **Make tests granular** - Each test should cover smallest area possible
 - **Make tests granular** - Each test should cover smallest area possible
 - Follow existing test patterns in respective test projects
 - Follow existing test patterns in respective test projects
+- **Avoid adding new tests to the `UnitTests` Project** - Make them parallelizable and add them to `UnitTests.Parallelizable`
+- **Avoid static dependencies** - DO NOT use the legacy/static `Application` API or `ConfigurationManager` in tests unless the tests explicitly test related functionality.
+- **Don't use `[AutoInitShutdown]` or `[SetupFakeApplication]`** - Legacy pattern, being phased out
 
 
 ### Test Configuration
 ### Test Configuration
 
 
 - `xunit.runner.json` - xUnit configuration
 - `xunit.runner.json` - xUnit configuration
 - `coverlet.runsettings` - Coverage settings (OpenCover format)
 - `coverlet.runsettings` - Coverage settings (OpenCover format)
 
 
----
-
 ## API Documentation Requirements
 ## API Documentation Requirements
 
 
 **All public APIs MUST have XML documentation:**
 **All public APIs MUST have XML documentation:**
@@ -202,16 +195,15 @@ dotnet run --project Examples/UICatalog/UICatalog.csproj
 - Complex topics → `docfx/docs/*.md` files
 - Complex topics → `docfx/docs/*.md` files
 - Proper English and grammar - Clear, concise, complete. Use imperative mood.
 - Proper English and grammar - Clear, concise, complete. Use imperative mood.
 
 
----
-
 ## Pull Request Guidelines
 ## Pull Request Guidelines
 
 
 ### PR Requirements
 ### PR Requirements
 
 
+- **ALWAYS** include instructions for pulling down locally at end of Description
+
 - **Title**: "Fixes #issue. Terse description". If multiple issues, list all, separated by commas (e.g. "Fixes #123, #456. Terse description")
 - **Title**: "Fixes #issue. Terse description". If multiple issues, list all, separated by commas (e.g. "Fixes #123, #456. Terse description")
 - **Description**: 
 - **Description**: 
   - Include "- Fixes #issue" for each issue near the top
   - Include "- Fixes #issue" for each issue near the top
-  - **ALWAYS** include instructions for pulling down locally at end of Description
   - Suggest user setup a remote named `copilot` pointing to your fork
   - Suggest user setup a remote named `copilot` pointing to your fork
   - Example:
   - Example:
     ```markdown
     ```markdown
@@ -220,99 +212,14 @@ dotnet run --project Examples/UICatalog/UICatalog.csproj
     git fetch copilot <branch-name>
     git fetch copilot <branch-name>
     git checkout copilot/<branch-name>
     git checkout copilot/<branch-name>
     ```
     ```
-- **Coding Style**: Follow all coding conventions in this document for new and modified code
 - **Tests**: Add tests for new functionality (see [Testing Requirements](#testing-requirements))
 - **Tests**: Add tests for new functionality (see [Testing Requirements](#testing-requirements))
 - **Coverage**: Maintain or increase code coverage
 - **Coverage**: Maintain or increase code coverage
 - **Scenarios**: Update UICatalog scenarios when adding features
 - **Scenarios**: Update UICatalog scenarios when adding features
 - **Warnings**: **CRITICAL - PRs must not introduce any new warnings**
 - **Warnings**: **CRITICAL - PRs must not introduce any new warnings**
   - Any file modified in a PR that currently generates warnings **MUST** be fixed to remove those warnings
   - Any file modified in a PR that currently generates warnings **MUST** be fixed to remove those warnings
   - Exception: Warnings caused by `[Obsolete]` attributes can remain
   - Exception: Warnings caused by `[Obsolete]` attributes can remain
-  - Expected baseline: ~326 warnings (mostly nullable reference warnings, unused variables, xUnit suggestions)
   - Action: Before submitting a PR, verify your changes don't add new warnings and fix any warnings in files you modify
   - Action: Before submitting a PR, verify your changes don't add new warnings and fix any warnings in files you modify
 
 
----
-
-## CI/CD Workflows
-
-The repository uses multiple GitHub Actions workflows. What runs and when:
-
-### 1) Build Solution (`.github/workflows/build.yml`)
-
-- **Triggers**: push and pull_request to `v2_release`, `v2_develop` (ignores `**.md`); supports `workflow_call`
-- **Runner/timeout**: `ubuntu-latest`, 10 minutes
-- **Steps**:
-- Checkout and setup .NET 8.x GA
-- `dotnet restore`
-- Build Debug: `dotnet build --configuration Debug --no-restore -property:NoWarn=0618%3B0612`
-- Build Release (library): `dotnet build Terminal.Gui/Terminal.Gui.csproj --configuration Release --no-incremental --force -property:NoWarn=0618%3B0612`
-- Pack Release: `dotnet pack Terminal.Gui/Terminal.Gui.csproj --configuration Release --output ./local_packages -property:NoWarn=0618%3B0612`
-- Restore NativeAot/SelfContained examples, then restore solution again
-- Build Release for `Examples/NativeAot` and `Examples/SelfContained`
-- Build Release solution
-- Upload artifacts named `build-artifacts`, retention 1 day
-
-### 2) Build & Run Unit Tests (`.github/workflows/unit-tests.yml`)
-
-- **Triggers**: push and pull_request to `v2_release`, `v2_develop` (ignores `**.md`)
-- **Matrix**: Ubuntu/Windows/macOS
-- **Timeout**: 15 minutes per job
-- **Process**:
-1. Calls build workflow to build solution once
-2. Downloads build artifacts
-3. Runs `dotnet restore` (required for `--no-build` to work)
-4. **Performance optimizations**:
-   - Disables Windows Defender on Windows runners (significant speedup)
-   - Collects code coverage **only on Linux** (ubuntu-latest) for performance
-   - Windows and macOS skip coverage collection to reduce test time
-   - Increased blame-hang-timeout to 120s for Windows/macOS (60s for Linux)
-5. Runs two test jobs:
-   - **Non-parallel UnitTests**: `Tests/UnitTests` with blame/diag flags; `xunit.stopOnFail=false`
-   - **Parallel UnitTestsParallelizable**: `Tests/UnitTestsParallelizable` with blame/diag flags; `xunit.stopOnFail=false`
-6. Uploads test logs and diagnostic data from all runners
-7. **Uploads code coverage to Codecov only from Linux runner**
-
-**Test results**: All tests output to unified `TestResults/` directory at repository root
-
-### 3) Build & Run Integration Tests (`.github/workflows/integration-tests.yml`)
-
-- **Triggers**: push and pull_request to `v2_release`, `v2_develop` (ignores `**.md`)
-- **Matrix**: Ubuntu/Windows/macOS
-- **Timeout**: 15 minutes
-- **Process**:
-1. Calls build workflow
-2. Downloads build artifacts
-3. Runs `dotnet restore`
-4. **Performance optimizations** (same as unit tests):
-   - Disables Windows Defender on Windows runners
-   - Collects code coverage **only on Linux**
-   - Increased blame-hang-timeout to 120s for Windows/macOS
-5. Runs IntegrationTests with blame/diag flags; `xunit.stopOnFail=true`
-6. Uploads logs per-OS
-7. **Uploads coverage to Codecov only from Linux runner**
-
-### 4) Publish to NuGet (`.github/workflows/publish.yml`)
-
-- **Triggers**: push to `v2_release`, `v2_develop`, and tags `v*`(ignores `**.md`)
-- Uses GitVersion to compute SemVer, builds Release, packs with symbols, and pushes to NuGet.org using `NUGET_API_KEY`
-
-### 5) Build and publish API docs (`.github/workflows/api-docs.yml`)
-
-- **Triggers**: push to `v1_release` and `v2_develop`
-- Builds DocFX site on Windows and deploys to GitHub Pages when `ref_name` is `v2_release` or `v2_develop`
-
-
-### Replicating CI Locally
-
-```bash
-# Full CI sequence:
-dotnet restore
-dotnet build --configuration Debug --no-restore
-dotnet test Tests/UnitTests --no-build --verbosity normal
-dotnet test Tests/UnitTestsParallelizable --no-build --verbosity normal
-dotnet build --configuration Release --no-restore
-```
-
----
 
 
 ## Repository Structure
 ## Repository Structure
 
 
@@ -364,7 +271,6 @@ dotnet build --configuration Release --no-restore
 
 
 **`/.github/workflows/`** - CI/CD pipelines (see [CI/CD Workflows](#cicd-workflows))
 **`/.github/workflows/`** - CI/CD pipelines (see [CI/CD Workflows](#cicd-workflows))
 
 
----
 
 
 ## Branching Model
 ## Branching Model
 
 
@@ -374,31 +280,6 @@ dotnet build --configuration Release --no-restore
 - `v2_release` - Stable releases, matches NuGet
 - `v2_release` - Stable releases, matches NuGet
 - `v1_develop`, `v1_release` - Legacy v1 (maintenance only)
 - `v1_develop`, `v1_release` - Legacy v1 (maintenance only)
 
 
----
-
-## Key Architecture Concepts
-
-**⚠️ CRITICAL - Contributors should understand these concepts before starting work.**
-
-See `/docfx/docs/` for deep dives on:
-
-- **Application Lifecycle** - How `Application.Init`, `Application.Run`, and `Application.Shutdown` work
-- **View Hierarchy** - Understanding `View`, `Toplevel`, `Window`, and view containment
-- **Layout System** - Pos, Dim, and automatic layout
-- **Event System** - How keyboard, mouse, and application events flow
-- **Driver Architecture** - How console drivers abstract platform differences
-- **Drawing Model** - How rendering works with Attributes, Colors, and Glyphs
-
-Key documentation:
-- [View Documentation](https://gui-cs.github.io/Terminal.Gui/docs/View.html)
-- [Events Deep Dive](https://gui-cs.github.io/Terminal.Gui/docs/events.html)
-- [Layout System](https://gui-cs.github.io/Terminal.Gui/docs/layout.html)
-- [Keyboard Handling](https://gui-cs.github.io/Terminal.Gui/docs/keyboard.html)
-- [Mouse Support](https://gui-cs.github.io/Terminal.Gui/docs/mouse.html)
-- [Drivers](https://gui-cs.github.io/Terminal.Gui/docs/drivers.html)
-
----
-
 ## What NOT to Do
 ## What NOT to Do
 
 
 - ❌ Don't add new linters/formatters (use existing)
 - ❌ Don't add new linters/formatters (use existing)
@@ -412,17 +293,4 @@ Key documentation:
 - ❌ **Don't use redundant type names with `new`** (**ALWAYS PREFER** target-typed `new ()`)
 - ❌ **Don't use redundant type names with `new`** (**ALWAYS PREFER** target-typed `new ()`)
 - ❌ **Don't introduce new warnings** (fix warnings in files you modify; exception: `[Obsolete]` warnings)
 - ❌ **Don't introduce new warnings** (fix warnings in files you modify; exception: `[Obsolete]` warnings)
 
 
----
-
-## Additional Resources
-
-- **Full Documentation**: https://gui-cs.github.io/Terminal.Gui
-- **API Reference**: https://gui-cs.github.io/Terminal.Gui/api/Terminal.Gui.App.html
-- **Deep Dives**: `/docfx/docs/` directory
-- **Getting Started**: https://gui-cs.github.io/Terminal.Gui/docs/getting-started.html
-- **Migrating from v1 to v2**: https://gui-cs.github.io/Terminal.Gui/docs/migratingfromv1.html
-- **Showcase**: https://gui-cs.github.io/Terminal.Gui/docs/showcase.html
-
----
-
 **Thank you for contributing to Terminal.Gui!** 🎉
 **Thank you for contributing to Terminal.Gui!** 🎉

+ 1 - 1
Directory.Packages.props

@@ -18,7 +18,7 @@
     <PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="[9.0.0,10)" />
     <PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="[9.0.0,10)" />
     <PackageVersion Include="Microsoft.Extensions.Logging" Version="9.0.6" />
     <PackageVersion Include="Microsoft.Extensions.Logging" Version="9.0.6" />
     <PackageVersion Include="System.IO.Abstractions" Version="[22.0.16,23)" />
     <PackageVersion Include="System.IO.Abstractions" Version="[22.0.16,23)" />
-    <PackageVersion Include="Wcwidth" Version="[3.0.0,)" />
+    <PackageVersion Include="Wcwidth" Version="[4.0.0,)" />
     <PackageVersion Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="[1.21.2,2)" />
     <PackageVersion Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="[1.21.2,2)" />
     <PackageVersion Include="Serilog" Version="4.2.0" />
     <PackageVersion Include="Serilog" Version="4.2.0" />
     <PackageVersion Include="Serilog.Extensions.Logging" Version="9.0.0" />
     <PackageVersion Include="Serilog.Extensions.Logging" Version="9.0.0" />

+ 0 - 2
Examples/CommunityToolkitExample/LoginView.cs

@@ -64,8 +64,6 @@ internal partial class LoginView : IRecipient<Message<LoginActions>>
                 }
                 }
         }
         }
         SetText ();
         SetText ();
-        // BUGBUG: This should not be needed:
-        Application.LayoutAndDraw ();
     }
     }
 
 
     private void SetText ()
     private void SetText ()

+ 4 - 4
Examples/CommunityToolkitExample/LoginViewModel.cs

@@ -12,7 +12,7 @@ internal partial class LoginViewModel : ObservableObject
     private const string INVALID_LOGIN_MESSAGE = "Please enter a valid user name and password.";
     private const string INVALID_LOGIN_MESSAGE = "Please enter a valid user name and password.";
     private const string LOGGING_IN_PROGRESS_MESSAGE = "Logging in...";
     private const string LOGGING_IN_PROGRESS_MESSAGE = "Logging in...";
     private const string VALID_LOGIN_MESSAGE = "The input is valid!";
     private const string VALID_LOGIN_MESSAGE = "The input is valid!";
-    
+
     [ObservableProperty]
     [ObservableProperty]
     private bool _canLogin;
     private bool _canLogin;
 
 
@@ -28,7 +28,7 @@ internal partial class LoginViewModel : ObservableObject
 
 
     [ObservableProperty]
     [ObservableProperty]
     private string _usernameLengthMessage;
     private string _usernameLengthMessage;
-    
+
     [ObservableProperty]
     [ObservableProperty]
     private Scheme? _validationScheme;
     private Scheme? _validationScheme;
 
 
@@ -105,7 +105,7 @@ internal partial class LoginViewModel : ObservableObject
     {
     {
         switch (loginAction)
         switch (loginAction)
         {
         {
-             case LoginActions.Clear:
+            case LoginActions.Clear:
                 LoginProgressMessage = message;
                 LoginProgressMessage = message;
                 ValidationMessage = INVALID_LOGIN_MESSAGE;
                 ValidationMessage = INVALID_LOGIN_MESSAGE;
                 ValidationScheme = SchemeManager.GetScheme ("Error");
                 ValidationScheme = SchemeManager.GetScheme ("Error");
@@ -115,7 +115,7 @@ internal partial class LoginViewModel : ObservableObject
                 break;
                 break;
             case LoginActions.Validation:
             case LoginActions.Validation:
                 ValidationMessage = CanLogin ? VALID_LOGIN_MESSAGE : INVALID_LOGIN_MESSAGE;
                 ValidationMessage = CanLogin ? VALID_LOGIN_MESSAGE : INVALID_LOGIN_MESSAGE;
-                ValidationScheme = CanLogin ? SchemeManager.GetScheme ("Base") : SchemeManager.GetScheme("Error");
+                ValidationScheme = CanLogin ? SchemeManager.GetScheme ("Base") : SchemeManager.GetScheme ("Error");
                 break;
                 break;
         }
         }
         WeakReferenceMessenger.Default.Send (new Message<LoginActions> { Value = loginAction });
         WeakReferenceMessenger.Default.Send (new Message<LoginActions> { Value = loginAction });

+ 0 - 1
Examples/CommunityToolkitExample/Message.cs

@@ -1,5 +1,4 @@
 namespace CommunityToolkitExample;
 namespace CommunityToolkitExample;
-
 internal class Message<T>
 internal class Message<T>
 {
 {
     public T? Value { get; set; }
     public T? Value { get; set; }

+ 7 - 8
Examples/CommunityToolkitExample/Program.cs

@@ -1,8 +1,6 @@
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.DependencyInjection;
-using Terminal.Gui.Configuration;
 using Terminal.Gui.App;
 using Terminal.Gui.App;
-using Terminal.Gui.ViewBase;
-
+using Terminal.Gui.Configuration;
 
 
 namespace CommunityToolkitExample;
 namespace CommunityToolkitExample;
 
 
@@ -14,10 +12,10 @@ public static class Program
     {
     {
         ConfigurationManager.Enable (ConfigLocations.All);
         ConfigurationManager.Enable (ConfigLocations.All);
         Services = ConfigureServices ();
         Services = ConfigureServices ();
-        Application.Init ();
-        Application.Run (Services.GetRequiredService<LoginView> ());
-        Application.Current?.Dispose ();
-        Application.Shutdown ();
+        using IApplication app = Application.Create ();
+        app.Init ();
+        using var loginView = Services.GetRequiredService<LoginView> ();
+        app.Run (loginView);
     }
     }
 
 
     private static IServiceProvider ConfigureServices ()
     private static IServiceProvider ConfigureServices ()
@@ -25,6 +23,7 @@ public static class Program
         var services = new ServiceCollection ();
         var services = new ServiceCollection ();
         services.AddTransient<LoginView> ();
         services.AddTransient<LoginView> ();
         services.AddTransient<LoginViewModel> ();
         services.AddTransient<LoginViewModel> ();
+
         return services.BuildServiceProvider ();
         return services.BuildServiceProvider ();
     }
     }
-}
+}

+ 25 - 21
Examples/CommunityToolkitExample/README.md

@@ -6,9 +6,10 @@ Right away we use IoC to load our views and view models.
 
 
 ``` csharp
 ``` csharp
 // As a public property for access further in the application if needed. 
 // As a public property for access further in the application if needed. 
-public static IServiceProvider Services { get; private set; }
+public static IServiceProvider? Services { get; private set; }
 ...
 ...
 // In Main
 // In Main
+ConfigurationManager.Enable (ConfigLocations.All);
 Services = ConfigureServices ();
 Services = ConfigureServices ();
 ...
 ...
 private static IServiceProvider ConfigureServices ()
 private static IServiceProvider ConfigureServices ()
@@ -20,16 +21,19 @@ private static IServiceProvider ConfigureServices ()
 }
 }
 ```
 ```
 
 
-Now, we start the app and get our main view.
+Now, we start the app using the modern Terminal.Gui model and get our main view.
 
 
 ``` csharp
 ``` csharp
-Application.Run (Services.GetRequiredService<LoginView> ());
+using IApplication app = Application.Create ();
+app.Init ();
+using var loginView = Services.GetRequiredService<LoginView> ();
+app.Run (loginView);
 ```
 ```
 
 
 Our view implements `IRecipient<T>` to demonstrate the use of the `WeakReferenceMessenger`. The binding of the view events is then created.
 Our view implements `IRecipient<T>` to demonstrate the use of the `WeakReferenceMessenger`. The binding of the view events is then created.
 
 
 ``` csharp
 ``` csharp
-internal partial class LoginView : IRecipient<Message<LoginAction>>
+internal partial class LoginView : IRecipient<Message<LoginActions>>
 {
 {
     public LoginView (LoginViewModel viewModel)
     public LoginView (LoginViewModel viewModel)
     {
     {
@@ -41,15 +45,16 @@ internal partial class LoginView : IRecipient<Message<LoginAction>>
         passwordInput.TextChanged += (_, _) =>
         passwordInput.TextChanged += (_, _) =>
                                      {
                                      {
                                          ViewModel.Password = passwordInput.Text;
                                          ViewModel.Password = passwordInput.Text;
-                                         SetText ();
                                      };
                                      };
-        loginButton.Accept += (_, _) =>
+        loginButton.Accepting += (_, e) =>
                               {
                               {
                                   if (!ViewModel.CanLogin) { return; }
                                   if (!ViewModel.CanLogin) { return; }
                                   ViewModel.LoginCommand.Execute (null);
                                   ViewModel.LoginCommand.Execute (null);
+                                  // When Accepting is handled, set e.Handled to true to prevent further processing.
+                                  e.Handled = true;
                               };
                               };
         ...
         ...
-        // Let the view model know the view is intialized.
+        // Let the view model know the view is initialized.
         Initialized += (_, _) => { ViewModel.Initialized (); };
         Initialized += (_, _) => { ViewModel.Initialized (); };
     }
     }
     ...
     ...
@@ -101,54 +106,53 @@ The use of `WeakReferenceMessenger` provides one method of signaling the view fr
 ...
 ...
 private async Task Login ()
 private async Task Login ()
 {
 {
-    SendMessage (LoginAction.LoginProgress, LOGGING_IN_PROGRESS_MESSAGE);
+    SendMessage (LoginActions.LoginProgress, LOGGING_IN_PROGRESS_MESSAGE);
     await Task.Delay (TimeSpan.FromSeconds (1));
     await Task.Delay (TimeSpan.FromSeconds (1));
     Clear ();
     Clear ();
 }
 }
 
 
-private void SendMessage (LoginAction loginAction, string message = "")
+private void SendMessage (LoginActions loginAction, string message = "")
 {
 {
     switch (loginAction)
     switch (loginAction)
     {
     {
-        case LoginAction.LoginProgress:
+        case LoginActions.LoginProgress:
             LoginProgressMessage = message;
             LoginProgressMessage = message;
             break;
             break;
-        case LoginAction.Validation:
+        case LoginActions.Validation:
             ValidationMessage = CanLogin ? VALID_LOGIN_MESSAGE : INVALID_LOGIN_MESSAGE;
             ValidationMessage = CanLogin ? VALID_LOGIN_MESSAGE : INVALID_LOGIN_MESSAGE;
-            ValidationScheme = CanLogin ? Colors.Schemes ["Base"] : Colors.Schemes ["Error"];
+            ValidationScheme = CanLogin ? SchemeManager.GetScheme ("Base") : SchemeManager.GetScheme ("Error");
             break;
             break;
     }
     }
-    WeakReferenceMessenger.Default.Send (new Message<LoginAction> { Value = loginAction });
+    WeakReferenceMessenger.Default.Send (new Message<LoginActions> { Value = loginAction });
 }
 }
 
 
 private void ValidateLogin ()
 private void ValidateLogin ()
 {
 {
     CanLogin = !string.IsNullOrEmpty (Username) && !string.IsNullOrEmpty (Password);
     CanLogin = !string.IsNullOrEmpty (Username) && !string.IsNullOrEmpty (Password);
-    SendMessage (LoginAction.Validation);
+    SendMessage (LoginActions.Validation);
 }
 }
 ...
 ...
 ```
 ```
 
 
-And the view's `Receive` function which provides an `Application.Refresh()` call to update the UI immediately.
+The view's `Receive` function updates the UI based on messages from the view model. In the modern Terminal.Gui model, UI updates are automatically refreshed, so no manual `Application.Refresh()` call is needed.
 
 
 ``` csharp
 ``` csharp
-public void Receive (Message<LoginAction> message)
+public void Receive (Message<LoginActions> message)
 {
 {
     switch (message.Value)
     switch (message.Value)
     {
     {
-        case LoginAction.LoginProgress:
+        case LoginActions.LoginProgress:
             {
             {
                 loginProgressLabel.Text = ViewModel.LoginProgressMessage;
                 loginProgressLabel.Text = ViewModel.LoginProgressMessage;
                 break;
                 break;
             }
             }
-        case LoginAction.Validation:
+        case LoginActions.Validation:
             {
             {
                 validationLabel.Text = ViewModel.ValidationMessage;
                 validationLabel.Text = ViewModel.ValidationMessage;
-                validationLabel.Scheme = ViewModel.ValidationScheme;
+                validationLabel.SetScheme (ViewModel.ValidationScheme);
                 break;
                 break;
             }
             }
     }
     }
-    SetText();
-    Application.Refresh ();
+    SetText ();
 }
 }
 ```
 ```

+ 27 - 36
Examples/Example/Example.cs

@@ -3,30 +3,28 @@
 // This is a simple example application.  For the full range of functionality
 // This is a simple example application.  For the full range of functionality
 // see the UICatalog project
 // see the UICatalog project
 
 
-using Terminal.Gui.Configuration;
 using Terminal.Gui.App;
 using Terminal.Gui.App;
-using Terminal.Gui.Drawing;
+using Terminal.Gui.Configuration;
 using Terminal.Gui.ViewBase;
 using Terminal.Gui.ViewBase;
 using Terminal.Gui.Views;
 using Terminal.Gui.Views;
-using Attribute = Terminal.Gui.Drawing.Attribute;
 
 
 // Override the default configuration for the application to use the Light theme
 // Override the default configuration for the application to use the Light theme
-//ConfigurationManager.RuntimeConfig = """{ "Theme": "Light" }""";
-ConfigurationManager.Enable(ConfigLocations.All);
-
+ConfigurationManager.RuntimeConfig = """{ "Theme": "Light" }""";
+ConfigurationManager.Enable (ConfigLocations.All);
 
 
+IApplication app = Application.Create ();
 
 
-Application.Run<ExampleWindow> ().Dispose ();
+app.Run<ExampleWindow> ();
 
 
-// Before the application exits, reset Terminal.Gui for clean shutdown
-Application.Shutdown ();
+// Dispose the app to clean up and enable Console.WriteLine below
+app.Dispose ();
 
 
 // To see this output on the screen it must be done after shutdown,
 // To see this output on the screen it must be done after shutdown,
 // which restores the previous screen.
 // which restores the previous screen.
 Console.WriteLine ($@"Username: {ExampleWindow.UserName}");
 Console.WriteLine ($@"Username: {ExampleWindow.UserName}");
 
 
 // Defines a top-level window with border and title
 // Defines a top-level window with border and title
-public class ExampleWindow : Window
+public sealed class ExampleWindow : Window
 {
 {
     public static string UserName { get; set; }
     public static string UserName { get; set; }
 
 
@@ -74,39 +72,32 @@ public class ExampleWindow : Window
 
 
         // When login button is clicked display a message popup
         // When login button is clicked display a message popup
         btnLogin.Accepting += (s, e) =>
         btnLogin.Accepting += (s, e) =>
-                           {
-                               if (userNameText.Text == "admin" && passwordText.Text == "password")
-                               {
-                                   MessageBox.Query ("Logging In", "Login Successful", "Ok");
-                                   UserName = userNameText.Text;
-                                   Application.RequestStop ();
-                               }
-                               else
-                               {
-                                   MessageBox.ErrorQuery ("Logging In", "Incorrect username or password", "Ok");
-                               }
-                               // When Accepting is handled, set e.Handled to true to prevent further processing.
-                               e.Handled = true;
-                           };
+                              {
+                                  if (userNameText.Text == "admin" && passwordText.Text == "password")
+                                  {
+                                      MessageBox.Query (App, "Logging In", "Login Successful", "Ok");
+                                      UserName = userNameText.Text;
+                                      Application.RequestStop ();
+                                  }
+                                  else
+                                  {
+                                      MessageBox.ErrorQuery (App, "Logging In", "Incorrect username or password", "Ok");
+                                  }
+
+                                  // When Accepting is handled, set e.Handled to true to prevent further processing.
+                                  e.Handled = true;
+                              };
 
 
         // Add the views to the Window
         // Add the views to the Window
         Add (usernameLabel, userNameText, passwordLabel, passwordText, btnLogin);
         Add (usernameLabel, userNameText, passwordLabel, passwordText, btnLogin);
 
 
-        ListView lv = new ListView ()
+        var lv = new ListView
         {
         {
-            Y = Pos.AnchorEnd(),
-            Height= Dim.Auto(),
-            Width = Dim.Auto()
+            Y = Pos.AnchorEnd (),
+            Height = Dim.Auto (),
+            Width = Dim.Auto ()
         };
         };
         lv.SetSource (["One", "Two", "Three", "Four"]);
         lv.SetSource (["One", "Two", "Three", "Four"]);
         Add (lv);
         Add (lv);
     }
     }
-
-    public override void EndInit ()
-    {
-        base.EndInit ();
-        // Set the theme to "Anders" if it exists, otherwise use "Default"
-        ThemeManager.Theme = ThemeManager.GetThemeNames ().FirstOrDefault (x => x == "Anders") ?? "Default";
-    }
 }
 }
- 

+ 1 - 4
Examples/Example/README.md

@@ -1,11 +1,8 @@
 # Terminal.Gui C# Example
 # Terminal.Gui C# Example
 
 
-This example shows how to use the Terminal.Gui library to create a simple GUI application in C#.
+This example shows how to use the Terminal.Gui library to create a simple TUI application in C#.
 
 
 This is the same code found in the Terminal.Gui README.md file.
 This is the same code found in the Terminal.Gui README.md file.
 
 
 To explore the full range of functionality in Terminal.Gui, see the [UICatalog](../UICatalog) project
 To explore the full range of functionality in Terminal.Gui, see the [UICatalog](../UICatalog) project
 
 
-See [README.md](https://github.com/gui-cs/Terminal.Gui) for a list of all Terminal.Gui samples.
-
-Note, the old `demo.cs` example has been deleted because it was not a very good example. It can still be found in the [git history](https://github.com/gui-cs/Terminal.Gui/tree/v1.8.2).

+ 11 - 0
Examples/FluentExample/FluentExample.csproj

@@ -0,0 +1,11 @@
+<Project Sdk="Microsoft.NET.Sdk">
+  <PropertyGroup>
+    <OutputType>Exe</OutputType>
+    <TargetFramework>net8.0</TargetFramework>
+    <LangVersion>preview</LangVersion>
+    <Nullable>enable</Nullable>
+  </PropertyGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\Terminal.Gui\Terminal.Gui.csproj" />
+  </ItemGroup>
+</Project>

+ 109 - 0
Examples/FluentExample/Program.cs

@@ -0,0 +1,109 @@
+// Fluent API example demonstrating IRunnable with automatic disposal and result extraction
+
+using Terminal.Gui.App;
+using Terminal.Gui.Drawing;
+using Terminal.Gui.ViewBase;
+using Terminal.Gui.Views;
+
+IApplication? app = Application.Create ()
+                               .Init ()
+                               .Run<ColorPickerView> ();
+
+// Run the application with fluent API - automatically creates, runs, and disposes the runnable
+Color? result = app.GetResult () as Color?;
+
+// Shut down the app with Dispose before we can use Console.WriteLine
+app.Dispose ();
+
+if (result is { })
+{
+    Console.WriteLine (@$"Selected Color: {result}");
+}
+else
+{
+    Console.WriteLine (@"No color selected");
+}
+
+/// <summary>
+///     A runnable view that allows the user to select a color.
+///     Demonstrates the Runnable with type pattern with automatic disposal.
+/// </summary>
+public class ColorPickerView : Runnable<Color?>
+{
+    public ColorPickerView ()
+    {
+        Title = "Select a Color (Esc to quit)";
+        BorderStyle = LineStyle.Single;
+        Height = Dim.Auto ();
+        Width = Dim.Auto ();
+
+        // Add instructions
+        var instructions = new Label
+        {
+            Text = "Use arrow keys to select a color, Enter to accept",
+            X = Pos.Center (),
+            Y = 0
+        };
+
+        // Create color picker
+        ColorPicker colorPicker = new ()
+        {
+            X = Pos.Center (),
+            Y = Pos.Bottom (instructions),
+            Style = new ColorPickerStyle ()
+            {
+                ShowColorName = true,
+                ShowTextFields = true
+            }
+        };
+        colorPicker.ApplyStyleChanges ();
+
+        // Create OK button
+        Button okButton = new ()
+        {
+            Title = "_OK",
+            X = Pos.Align (Alignment.Center),
+            Y = Pos.AnchorEnd (),
+            IsDefault = true
+        };
+
+        okButton.Accepting += (s, e) =>
+                              {
+                                  // Extract result before stopping
+                                  Result = colorPicker.SelectedColor;
+                                  RequestStop ();
+                                  e.Handled = true;
+                              };
+
+        // Create Cancel button
+        Button cancelButton = new ()
+        {
+            Title = "_Cancel",
+            X = Pos.Align (Alignment.Center),
+            Y = Pos.AnchorEnd ()
+        };
+
+        cancelButton.Accepting += (s, e) =>
+                                  {
+                                      // Don't set result - leave as null
+                                      RequestStop ();
+                                      e.Handled = true;
+                                  };
+
+        // Add views
+        Add (instructions, colorPicker, okButton, cancelButton);
+    }
+
+    protected override bool OnIsRunningChanging (bool oldIsRunning, bool newIsRunning)
+    {
+        // Alternative place to extract result before stopping
+        // This is called before the view is removed from the stack
+        if (!newIsRunning && Result is null)
+        {
+            // User pressed Esc - could extract current selection here
+            //Result = SelectedColor;
+        }
+
+        return base.OnIsRunningChanging (oldIsRunning, newIsRunning);
+    }
+}

+ 2 - 2
Examples/NativeAot/Program.cs

@@ -101,13 +101,13 @@ public class ExampleWindow : Window
         {
         {
             if (userNameText.Text == "admin" && passwordText.Text == "password")
             if (userNameText.Text == "admin" && passwordText.Text == "password")
             {
             {
-                MessageBox.Query ("Logging In", "Login Successful", "Ok");
+                MessageBox.Query (App, "Logging In", "Login Successful", "Ok");
                 UserName = userNameText.Text;
                 UserName = userNameText.Text;
                 Application.RequestStop ();
                 Application.RequestStop ();
             }
             }
             else
             else
             {
             {
-                MessageBox.ErrorQuery ("Logging In", "Incorrect username or password", "Ok");
+                MessageBox.ErrorQuery (App, "Logging In", "Incorrect username or password", "Ok");
             }
             }
             // Anytime Accepting is handled, make sure to set e.Handled to true.
             // Anytime Accepting is handled, make sure to set e.Handled to true.
             e.Handled = true;
             e.Handled = true;

+ 7 - 8
Examples/ReactiveExample/Program.cs

@@ -1,9 +1,7 @@
 using System.Reactive.Concurrency;
 using System.Reactive.Concurrency;
 using ReactiveUI;
 using ReactiveUI;
-using ReactiveUI.SourceGenerators;
-using Terminal.Gui.Configuration;
 using Terminal.Gui.App;
 using Terminal.Gui.App;
-using Terminal.Gui.ViewBase;
+using Terminal.Gui.Configuration;
 
 
 namespace ReactiveExample;
 namespace ReactiveExample;
 
 
@@ -12,11 +10,12 @@ public static class Program
     private static void Main (string [] args)
     private static void Main (string [] args)
     {
     {
         ConfigurationManager.Enable (ConfigLocations.All);
         ConfigurationManager.Enable (ConfigLocations.All);
-        Application.Init ();
-        RxApp.MainThreadScheduler = TerminalScheduler.Default;
+        using IApplication app = Application.Create ();
+        app.Init ();
+        RxApp.MainThreadScheduler = new TerminalScheduler (app);
         RxApp.TaskpoolScheduler = TaskPoolScheduler.Default;
         RxApp.TaskpoolScheduler = TaskPoolScheduler.Default;
-        Application.Run (new LoginView (new LoginViewModel ()));
-        Application.Current.Dispose ();
-        Application.Shutdown ();
+        var loginView = new LoginView (new ());
+        app.Run (loginView);
+        loginView.Dispose ();
     }
     }
 }
 }

+ 8 - 4
Examples/ReactiveExample/README.md

@@ -7,10 +7,14 @@ This is a sample app that shows how to use `System.Reactive` and `ReactiveUI` wi
 In order to use reactive extensions scheduling, copy-paste the `TerminalScheduler.cs` file into your project, and add the following lines to the composition root of your `Terminal.Gui` application:
 In order to use reactive extensions scheduling, copy-paste the `TerminalScheduler.cs` file into your project, and add the following lines to the composition root of your `Terminal.Gui` application:
 
 
 ```cs
 ```cs
-Application.Init ();
-RxApp.MainThreadScheduler = TerminalScheduler.Default;
+ConfigurationManager.Enable (ConfigLocations.All);
+using IApplication app = Application.Create ();
+app.Init ();
+RxApp.MainThreadScheduler = new TerminalScheduler (app);
 RxApp.TaskpoolScheduler = TaskPoolScheduler.Default;
 RxApp.TaskpoolScheduler = TaskPoolScheduler.Default;
-Application.Run (new RootView (new RootViewModel ()));
+var loginView = new LoginView (new ());
+app.Run (loginView);
+loginView.Dispose ();
 ```
 ```
 
 
 From now on, you can use `.ObserveOn(RxApp.MainThreadScheduler)` to return to the main loop from a background thread. This is useful when you have a `IObservable<TValue>` updated from a background thread, and you wish to update the UI with `TValue`s received from that observable.
 From now on, you can use `.ObserveOn(RxApp.MainThreadScheduler)` to return to the main loop from a background thread. This is useful when you have a `IObservable<TValue>` updated from a background thread, and you wish to update the UI with `TValue`s received from that observable.
@@ -43,6 +47,6 @@ If you combine `OneWay` and `OneWayToSource` data bindings, you get `TwoWay` dat
 // 'clearButton' is 'Button'
 // 'clearButton' is 'Button'
 clearButton
 clearButton
 	.Events ()
 	.Events ()
-	.Clicked
+	.Accepting
 	.InvokeCommand (ViewModel, x => x.Clear);
 	.InvokeCommand (ViewModel, x => x.Clear);
 ```
 ```

+ 28 - 21
Examples/ReactiveExample/TerminalScheduler.cs

@@ -1,4 +1,4 @@
-using System;
+#nullable enable
 using System.Reactive.Concurrency;
 using System.Reactive.Concurrency;
 using System.Reactive.Disposables;
 using System.Reactive.Disposables;
 using Terminal.Gui.App;
 using Terminal.Gui.App;
@@ -7,8 +7,9 @@ namespace ReactiveExample;
 
 
 public class TerminalScheduler : LocalScheduler
 public class TerminalScheduler : LocalScheduler
 {
 {
-    public static readonly TerminalScheduler Default = new ();
-    private TerminalScheduler () { }
+    public TerminalScheduler (IApplication? application) { _application = application; }
+
+    private readonly IApplication? _application = null;
 
 
     public override IDisposable Schedule<TState> (
     public override IDisposable Schedule<TState> (
         TState state,
         TState state,
@@ -21,15 +22,15 @@ public class TerminalScheduler : LocalScheduler
             var composite = new CompositeDisposable (2);
             var composite = new CompositeDisposable (2);
             var cancellation = new CancellationDisposable ();
             var cancellation = new CancellationDisposable ();
 
 
-            Application.Invoke (
-                                (_) =>
-                                {
-                                    if (!cancellation.Token.IsCancellationRequested)
-                                    {
-                                        composite.Add (action (this, state));
-                                    }
-                                }
-                               );
+            _application?.Invoke (
+                                 (_) =>
+                                 {
+                                     if (!cancellation.Token.IsCancellationRequested)
+                                     {
+                                         composite.Add (action (this, state));
+                                     }
+                                 }
+                                );
             composite.Add (cancellation);
             composite.Add (cancellation);
 
 
             return composite;
             return composite;
@@ -39,16 +40,22 @@ public class TerminalScheduler : LocalScheduler
         {
         {
             var composite = new CompositeDisposable (2);
             var composite = new CompositeDisposable (2);
 
 
-            object timeout = Application.AddTimeout (
-                                                     dueTime,
-                                                     () =>
-                                                     {
-                                                         composite.Add (action (this, state));
+            object? timeout = _application?.AddTimeout (
+                                                      dueTime,
+                                                      () =>
+                                                      {
+                                                          composite.Add (action (this, state));
 
 
-                                                         return false;
-                                                     }
-                                                    );
-            composite.Add (Disposable.Create (() => Application.RemoveTimeout (timeout)));
+                                                          return false;
+                                                      }
+                                                     );
+            composite.Add (Disposable.Create (() =>
+                                              {
+                                                  if (timeout is { })
+                                                  {
+                                                      _application?.RemoveTimeout (timeout);
+                                                  }
+                                              }));
 
 
             return composite;
             return composite;
         }
         }

+ 1 - 2
Examples/ReactiveExample/ViewExtensions.cs

@@ -1,5 +1,4 @@
-using System;
-using Terminal.Gui.ViewBase;
+using Terminal.Gui.ViewBase;
 using Terminal.Gui.Views;
 using Terminal.Gui.Views;
 
 
 namespace ReactiveExample;
 namespace ReactiveExample;

+ 168 - 0
Examples/RunnableWrapperExample/Program.cs

@@ -0,0 +1,168 @@
+// Example demonstrating how to make ANY View runnable without implementing IRunnable
+
+using Terminal.Gui.App;
+using Terminal.Gui.Drawing;
+using Terminal.Gui.ViewBase;
+using Terminal.Gui.Views;
+
+IApplication app = Application.Create ();
+app.Init ();
+
+// Example 1: Use extension method with result extraction
+var textField = new TextField { Width = 40, Text = "Default text" };
+textField.Title = "Enter your name";
+textField.BorderStyle = LineStyle.Single;
+
+RunnableWrapper<TextField, string> textRunnable = textField.AsRunnable (tf => tf.Text);
+app.Run (textRunnable);
+
+if (textRunnable.Result is { } name)
+{
+    MessageBox.Query (app, "Result", $"You entered: {name}", "OK");
+}
+else
+{
+    MessageBox.Query (app, "Result", "Canceled", "OK");
+}
+
+textRunnable.Dispose ();
+
+// Example 2: Use IApplication.RunView() for one-liner
+Color selectedColor = app.RunView (
+                                   new ColorPicker
+                                   {
+                                       Title = "Pick a Color",
+                                       BorderStyle = LineStyle.Single
+                                   },
+                                   cp => cp.SelectedColor);
+
+MessageBox.Query (app, "Result", $"Selected color: {selectedColor}", "OK");
+
+// Example 3: FlagSelector with typed enum result
+FlagSelector<SelectorStyles> flagSelector = new()
+{
+    Title = "Choose Styles",
+    BorderStyle = LineStyle.Single
+};
+
+RunnableWrapper<FlagSelector<SelectorStyles>, SelectorStyles?> flagsRunnable = flagSelector.AsRunnable (fs => fs.Value);
+app.Run (flagsRunnable);
+
+MessageBox.Query (app, "Result", $"Selected styles: {flagsRunnable.Result}", "OK");
+flagsRunnable.Dispose ();
+
+// Example 4: Any View without result extraction
+var label = new Label
+{
+    Text = "Press Esc to continue...",
+    X = Pos.Center (),
+    Y = Pos.Center ()
+};
+
+RunnableWrapper<Label, object> labelRunnable = label.AsRunnable ();
+app.Run (labelRunnable);
+
+// Can still access the wrapped view
+MessageBox.Query (app, "Result", $"Label text was: {labelRunnable.WrappedView.Text}", "OK");
+labelRunnable.Dispose ();
+
+// Example 5: Complex custom View made runnable
+View formView = CreateCustomForm ();
+RunnableWrapper<View, FormData> formRunnable = formView.AsRunnable (ExtractFormData);
+
+app.Run (formRunnable);
+
+if (formRunnable.Result is { } formData)
+{
+    MessageBox.Query (
+                      app,
+                      "Form Results",
+                      $"Name: {formData.Name}\nAge: {formData.Age}\nAgreed: {formData.Agreed}",
+                      "OK");
+}
+
+formRunnable.Dispose ();
+
+app.Dispose ();
+
+// Helper method to create a custom form
+View CreateCustomForm ()
+{
+    var form = new View
+    {
+        Title = "User Information",
+        BorderStyle = LineStyle.Single,
+        Width = 50,
+        Height = 10
+    };
+
+    var nameField = new TextField
+    {
+        Id = "nameField",
+        X = 10,
+        Y = 1,
+        Width = 30
+    };
+
+    var ageField = new TextField
+    {
+        Id = "ageField",
+        X = 10,
+        Y = 3,
+        Width = 10
+    };
+
+    var agreeCheckbox = new CheckBox
+    {
+        Id = "agreeCheckbox",
+        Title = "I agree to terms",
+        X = 10,
+        Y = 5
+    };
+
+    var okButton = new Button
+    {
+        Title = "OK",
+        X = Pos.Center (),
+        Y = 7,
+        IsDefault = true
+    };
+
+    okButton.Accepting += (s, e) =>
+                          {
+                              form.App?.RequestStop ();
+                              e.Handled = true;
+                          };
+
+    form.Add (new Label { Text = "Name:", X = 2, Y = 1 });
+    form.Add (nameField);
+    form.Add (new Label { Text = "Age:", X = 2, Y = 3 });
+    form.Add (ageField);
+    form.Add (agreeCheckbox);
+    form.Add (okButton);
+
+    return form;
+}
+
+// Helper method to extract data from the custom form
+FormData ExtractFormData (View form)
+{
+    var nameField = form.SubViews.FirstOrDefault (v => v.Id == "nameField") as TextField;
+    var ageField = form.SubViews.FirstOrDefault (v => v.Id == "ageField") as TextField;
+    var agreeCheckbox = form.SubViews.FirstOrDefault (v => v.Id == "agreeCheckbox") as CheckBox;
+
+    return new()
+    {
+        Name = nameField?.Text ?? string.Empty,
+        Age = int.TryParse (ageField?.Text, out int age) ? age : 0,
+        Agreed = agreeCheckbox?.CheckedState == CheckState.Checked
+    };
+}
+
+// Result type for custom form
+internal record FormData
+{
+    public string Name { get; init; } = string.Empty;
+    public int Age { get; init; }
+    public bool Agreed { get; init; }
+}

+ 15 - 0
Examples/RunnableWrapperExample/RunnableWrapperExample.csproj

@@ -0,0 +1,15 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <OutputType>Exe</OutputType>
+    <TargetFramework>net8.0</TargetFramework>
+    <ImplicitUsings>enable</ImplicitUsings>
+    <Nullable>enable</Nullable>
+    <LangVersion>latest</LangVersion>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <ProjectReference Include="..\..\Terminal.Gui\Terminal.Gui.csproj" />
+  </ItemGroup>
+
+</Project>

+ 15 - 15
Examples/SelfContained/Program.cs

@@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis;
 using System.Globalization;
 using System.Globalization;
 using Terminal.Gui.Configuration;
 using Terminal.Gui.Configuration;
 using Terminal.Gui.App;
 using Terminal.Gui.App;
+using Terminal.Gui.Drawing;
 using Terminal.Gui.ViewBase;
 using Terminal.Gui.ViewBase;
 using Terminal.Gui.Views;
 using Terminal.Gui.Views;
 
 
@@ -16,7 +17,9 @@ public static class Program
     private static void Main (string [] args)
     private static void Main (string [] args)
     {
     {
         ConfigurationManager.Enable (ConfigLocations.All);
         ConfigurationManager.Enable (ConfigLocations.All);
-        Application.Init ();
+
+        IApplication app = Application.Create ();
+        app.Init ();
 
 
         #region The code in this region is not intended for use in a self-contained single-file. It's just here to make sure there is no functionality break with localization in Terminal.Gui using single-file
         #region The code in this region is not intended for use in a self-contained single-file. It's just here to make sure there is no functionality break with localization in Terminal.Gui using single-file
 
 
@@ -33,28 +36,25 @@ public static class Program
 
 
         #endregion
         #endregion
 
 
-        ExampleWindow app = new ();
-        Application.Run (app);
+        using ExampleWindow exampleWindow = new ();
+        string? userName = app.Run (exampleWindow) as string;
 
 
-        // Dispose the app object before shutdown
-        app.Dispose ();
 
 
-        // Before the application exits, reset Terminal.Gui for clean shutdown
-        Application.Shutdown ();
+        // Shutdown the application in order to free resources and clean up the terminal
+        app.Dispose ();
 
 
         // To see this output on the screen it must be done after shutdown,
         // To see this output on the screen it must be done after shutdown,
         // which restores the previous screen.
         // which restores the previous screen.
-        Console.WriteLine ($@"Username: {ExampleWindow.UserName}");
+        Console.WriteLine ($@"Username: {userName}");
     }
     }
 }
 }
 
 
 // Defines a top-level window with border and title
 // Defines a top-level window with border and title
-public class ExampleWindow : Window
+public class ExampleWindow : Runnable<string>
 {
 {
-    public static string? UserName;
-
     public ExampleWindow ()
     public ExampleWindow ()
     {
     {
+        BorderStyle = LineStyle.Single;
         Title = $"Example App ({Application.QuitKey} to quit)";
         Title = $"Example App ({Application.QuitKey} to quit)";
 
 
         // Create input components and labels
         // Create input components and labels
@@ -100,13 +100,13 @@ public class ExampleWindow : Window
                            {
                            {
                                if (userNameText.Text == "admin" && passwordText.Text == "password")
                                if (userNameText.Text == "admin" && passwordText.Text == "password")
                                {
                                {
-                                   MessageBox.Query ("Logging In", "Login Successful", "Ok");
-                                   UserName = userNameText.Text;
-                                   Application.RequestStop ();
+                                   MessageBox.Query (App, "Logging In", "Login Successful", "Ok");
+                                   Result = userNameText.Text;
+                                   App?.RequestStop ();
                                }
                                }
                                else
                                else
                                {
                                {
-                                   MessageBox.ErrorQuery ("Logging In", "Incorrect username or password", "Ok");
+                                   MessageBox.ErrorQuery (App, "Logging In", "Incorrect username or password", "Ok");
                                }
                                }
                                // When Accepting is handled, set e.Handled to true to prevent further processing.
                                // When Accepting is handled, set e.Handled to true to prevent further processing.
                                e.Handled = true;
                                e.Handled = true;

+ 26 - 0
Examples/SelfContained/README.md

@@ -2,6 +2,32 @@
 
 
 This project aims to test the `Terminal.Gui` library to create a simple `self-contained` `single-file` GUI application in C#, ensuring that all its features are available.
 This project aims to test the `Terminal.Gui` library to create a simple `self-contained` `single-file` GUI application in C#, ensuring that all its features are available.
 
 
+## Modern Terminal.Gui API
+
+This example uses the modern Terminal.Gui application model:
+
+```csharp
+ConfigurationManager.Enable (ConfigLocations.All);
+
+IApplication app = Application.Create ();
+app.Init ();
+
+using ExampleWindow exampleWindow = new ();
+string? userName = app.Run (exampleWindow) as string;
+
+app.Dispose ();
+
+Console.WriteLine ($@"Username: {userName}");
+```
+
+Key aspects of the modern model:
+- Use `Application.Create()` to create an `IApplication` instance
+- Call `app.Init()` to initialize the application
+- Use `app.Run(view)` to run views with proper resource management
+- Call `app.Dispose()` to clean up resources and restore the terminal
+- Event handling uses `Accepting` event instead of legacy `Accept` event
+- Set `e.Handled = true` in event handlers to prevent further processing
+
 With `Debug` the `.csproj` is used and with `Release` the latest `nuget package` is used, either in `Solution Configurations` or in `Profile Publish`.
 With `Debug` the `.csproj` is used and with `Release` the latest `nuget package` is used, either in `Solution Configurations` or in `Profile Publish`.
 
 
 To publish the self-contained single file in `Debug` or `Release` mode, it is not necessary to select it in the `Solution Configurations`, just choose the `Debug` or `Release` configuration in the `Publish Profile`.
 To publish the self-contained single file in `Debug` or `Release` mode, it is not necessary to select it in the `Solution Configurations`, just choose the `Debug` or `Release` configuration in the `Publish Profile`.

+ 1 - 1
Examples/UICatalog/README.md

@@ -80,7 +80,7 @@ The default `Window` shows the Scenario name and supports exiting the Scenario t
 
 
 ![screenshot](generic_screenshot.png)
 ![screenshot](generic_screenshot.png)
 
 
-To build a more advanced scenario, where control of the `Toplevel` and `Window` is needed (e.g. for scenarios using `MenuBar` or `StatusBar`), simply use `Application.Top` per normal Terminal.Gui programming, as seen in the `Notepad` scenario.
+To build a more advanced scenario, where control of the `Runnable` and `Window` is needed (e.g. for scenarios using `MenuBar` or `StatusBar`), simply use `Application.Top` per normal Terminal.Gui programming, as seen in the `Notepad` scenario.
 
 
 For complete control, the `Init` and `Run` overrides can be implemented. The `base.Init` creates `Win`. The `base.Run` simply calls `Application.Run(Application.Top)`.
 For complete control, the `Init` and `Run` overrides can be implemented. The `base.Init` creates `Win`. The `base.Run` simply calls `Application.Run(Application.Top)`.
 
 

+ 4 - 4
Examples/UICatalog/Resources/config.json

@@ -11,7 +11,7 @@
       "Hot Dog Stand": {
       "Hot Dog Stand": {
         "Schemes": [
         "Schemes": [
           {
           {
-            "Toplevel": {
+            "Runnable": {
               "Normal": {
               "Normal": {
                 "Foreground": "Black",
                 "Foreground": "Black",
                 "Background": "#FFFF00"
                 "Background": "#FFFF00"
@@ -149,8 +149,8 @@
         "FrameView.DefaultBorderStyle": "Double",
         "FrameView.DefaultBorderStyle": "Double",
         "MessageBox.DefaultMinimumHeight": 0,
         "MessageBox.DefaultMinimumHeight": 0,
         "Button.DefaultHighlightStates": "In, Pressed",
         "Button.DefaultHighlightStates": "In, Pressed",
-        "Menuv2.DefaultBorderStyle": "Heavy",
-        "MenuBarv2.DefaultBorderStyle": "Heavy",
+        "Menu.DefaultBorderStyle": "Heavy",
+        "MenuBar.DefaultBorderStyle": "Heavy",
         "Schemes": [
         "Schemes": [
           {
           {
             "UI Catalog Scheme": {
             "UI Catalog Scheme": {
@@ -177,7 +177,7 @@
             }
             }
           },
           },
           {
           {
-            "TopLevel": {
+            "Runnable": {
               "Normal": {
               "Normal": {
                 "Foreground": "DarkGray",
                 "Foreground": "DarkGray",
                 "Background": "White"
                 "Background": "White"

+ 7 - 5
Examples/UICatalog/Scenario.cs

@@ -67,7 +67,7 @@ namespace UICatalog;
 ///         };
 ///         };
 /// 
 /// 
 ///         var button = new Button { X = Pos.Center (), Y = Pos.Center (), Text = "Press me!" };
 ///         var button = new Button { X = Pos.Center (), Y = Pos.Center (), Text = "Press me!" };
-///         button.Accept += (s, e) => MessageBox.ErrorQuery ("Error", "You pressed the button!", "Ok");
+///         button.Accept += (s, e) => MessageBox.ErrorQuery (App, "Error", "You pressed the button!", "Ok");
 ///         appWindow.Add (button);
 ///         appWindow.Add (button);
 /// 
 /// 
 ///         // Run - Start the application.
 ///         // Run - Start the application.
@@ -210,18 +210,20 @@ public class Scenario : IDisposable
         void OnClearedContents (object? sender, EventArgs args) => BenchmarkResults.ClearedContentCount++;
         void OnClearedContents (object? sender, EventArgs args) => BenchmarkResults.ClearedContentCount++;
     }
     }
 
 
-    private void OnApplicationOnIteration (object? s, IterationEventArgs a)
+    private void OnApplicationOnIteration (object? s, EventArgs<IApplication?> a)
     {
     {
         BenchmarkResults.IterationCount++;
         BenchmarkResults.IterationCount++;
         if (BenchmarkResults.IterationCount > BENCHMARK_MAX_NATURAL_ITERATIONS + (_demoKeys!.Count * BENCHMARK_KEY_PACING))
         if (BenchmarkResults.IterationCount > BENCHMARK_MAX_NATURAL_ITERATIONS + (_demoKeys!.Count * BENCHMARK_KEY_PACING))
         {
         {
-            Application.RequestStop ();
+            a.Value?.RequestStop ();
         }
         }
     }
     }
 
 
+    // BUGBUG: This is incompatible with modals. This should be using the new equivalent of Runnable.Ready 
+    // BUGBUG: which will be IsRunningChanged with newIsRunning == true
     private void OnApplicationSessionBegun (object? sender, SessionTokenEventArgs e)
     private void OnApplicationSessionBegun (object? sender, SessionTokenEventArgs e)
     {
     {
-        SubscribeAllSubViews (Application.Current!);
+        SubscribeAllSubViews (Application.TopRunnableView!);
 
 
         _demoKeys = GetDemoKeyStrokes ();
         _demoKeys = GetDemoKeyStrokes ();
 
 
@@ -241,7 +243,7 @@ public class Scenario : IDisposable
 
 
         return;
         return;
 
 
-        // Get a list of all subviews under Application.Current (and their subviews, etc.)
+        // Get a list of all subviews under Application.TopRunnable (and their subviews, etc.)
         // and subscribe to their DrawComplete event
         // and subscribe to their DrawComplete event
         void SubscribeAllSubViews (View view)
         void SubscribeAllSubViews (View view)
         {
         {

+ 8 - 8
Examples/UICatalog/Scenarios/Adornments.cs

@@ -11,7 +11,7 @@ public class Adornments : Scenario
     {
     {
         Application.Init ();
         Application.Init ();
 
 
-        Window app = new ()
+        Window appWindow = new ()
         {
         {
             Title = GetQuitKeyAndName (),
             Title = GetQuitKeyAndName (),
             BorderStyle = LineStyle.None
             BorderStyle = LineStyle.None
@@ -28,7 +28,7 @@ public class Adornments : Scenario
 
 
         editor.Border!.Thickness = new (1, 2, 1, 1);
         editor.Border!.Thickness = new (1, 2, 1, 1);
 
 
-        app.Add (editor);
+        appWindow.Add (editor);
 
 
         var window = new Window
         var window = new Window
         {
         {
@@ -38,7 +38,7 @@ public class Adornments : Scenario
             Width = Dim.Fill (Dim.Func (_ => editor.Frame.Width)),
             Width = Dim.Fill (Dim.Func (_ => editor.Frame.Width)),
             Height = Dim.Fill ()
             Height = Dim.Fill ()
         };
         };
-        app.Add (window);
+        appWindow.Add (window);
 
 
         var tf1 = new TextField { Width = 10, Text = "TextField" };
         var tf1 = new TextField { Width = 10, Text = "TextField" };
         var color = new ColorPicker16 { Title = "BG", BoxHeight = 1, BoxWidth = 1, X = Pos.AnchorEnd () };
         var color = new ColorPicker16 { Title = "BG", BoxHeight = 1, BoxWidth = 1, X = Pos.AnchorEnd () };
@@ -60,7 +60,7 @@ public class Adornments : Scenario
         var button = new Button { X = Pos.Center (), Y = Pos.Center (), Text = "Press me!" };
         var button = new Button { X = Pos.Center (), Y = Pos.Center (), Text = "Press me!" };
 
 
         button.Accepting += (s, e) =>
         button.Accepting += (s, e) =>
-                             MessageBox.Query (20, 7, "Hi", $"Am I a {window.GetType ().Name}?", "Yes", "No");
+                             MessageBox.Query (appWindow.App, 20, 7, "Hi", $"Am I a {window.GetType ().Name}?", "Yes", "No");
 
 
         var label = new TextView
         var label = new TextView
         {
         {
@@ -121,7 +121,7 @@ public class Adornments : Scenario
                                       Text = "text (Y = 1)",
                                       Text = "text (Y = 1)",
                                       CanFocus = true
                                       CanFocus = true
                                   };
                                   };
-                                  textFieldInPadding.Accepting += (s, e) => MessageBox.Query (20, 7, "TextField", textFieldInPadding.Text, "Ok");
+                                  textFieldInPadding.Accepting += (s, e) => MessageBox.Query (appWindow.App, 20, 7, "TextField", textFieldInPadding.Text, "Ok");
                                   window.Padding.Add (textFieldInPadding);
                                   window.Padding.Add (textFieldInPadding);
 
 
                                   var btnButtonInPadding = new Button
                                   var btnButtonInPadding = new Button
@@ -132,7 +132,7 @@ public class Adornments : Scenario
                                       CanFocus = true,
                                       CanFocus = true,
                                       HighlightStates = MouseState.None,
                                       HighlightStates = MouseState.None,
                                   };
                                   };
-                                  btnButtonInPadding.Accepting += (s, e) => MessageBox.Query (20, 7, "Hi", "Button in Padding Pressed!", "Ok");
+                                  btnButtonInPadding.Accepting += (s, e) => MessageBox.Query (appWindow.App, 20, 7, "Hi", "Button in Padding Pressed!", "Ok");
                                   btnButtonInPadding.BorderStyle = LineStyle.Dashed;
                                   btnButtonInPadding.BorderStyle = LineStyle.Dashed;
                                   btnButtonInPadding.Border!.Thickness = new (1, 1, 1, 1);
                                   btnButtonInPadding.Border!.Thickness = new (1, 1, 1, 1);
                                   window.Padding.Add (btnButtonInPadding);
                                   window.Padding.Add (btnButtonInPadding);
@@ -155,8 +155,8 @@ public class Adornments : Scenario
         editor.AutoSelectSuperView = window;
         editor.AutoSelectSuperView = window;
         editor.AutoSelectAdornments = true;
         editor.AutoSelectAdornments = true;
 
 
-        Application.Run (app);
-        app.Dispose ();
+        Application.Run (appWindow);
+        appWindow.Dispose ();
 
 
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }

+ 8 - 1
Examples/UICatalog/Scenarios/AllViewsTester.cs

@@ -28,7 +28,7 @@ public class AllViewsTester : Scenario
 
 
     public override void Main ()
     public override void Main ()
     {
     {
-        // Don't create a sub-win (Scenario.Win); just use Application.Current
+        // Don't create a sub-win (Scenario.Win); just use Application.TopRunnable
         Application.Init ();
         Application.Init ();
 
 
         var app = new Window
         var app = new Window
@@ -220,6 +220,13 @@ public class AllViewsTester : Scenario
     {
     {
         Debug.Assert (_curView is null);
         Debug.Assert (_curView is null);
 
 
+        // Skip RunnableWrapper types as they have generic constraints that cannot be satisfied
+        if (type.IsGenericType && type.GetGenericTypeDefinition().Name.StartsWith("RunnableWrapper"))
+        {
+            Logging.Warning ($"Cannot create an instance of {type.Name} because it is a RunnableWrapper with unsatisfiable generic constraints.");
+            return;
+        }
+
         // If we are to create a generic Type
         // If we are to create a generic Type
         if (type.IsGenericType)
         if (type.IsGenericType)
         {
         {

+ 1 - 1
Examples/UICatalog/Scenarios/AnimationScenario/AnimationScenario.cs

@@ -78,7 +78,7 @@ public class AnimationScenario : Scenario
         if (!f.Exists)
         if (!f.Exists)
         {
         {
             Debug.WriteLine ($"Could not find {f.FullName}");
             Debug.WriteLine ($"Could not find {f.FullName}");
-            MessageBox.ErrorQuery ("Could not find gif", $"Could not find\n{f.FullName}", "Ok");
+            MessageBox.ErrorQuery (_imageView?.App, "Could not find gif", $"Could not find\n{f.FullName}", "Ok");
 
 
             return;
             return;
         }
         }

+ 4 - 4
Examples/UICatalog/Scenarios/Arrangement.cs

@@ -183,9 +183,9 @@ public class Arrangement : Scenario
 
 
         datePicker.SetScheme (new Scheme (
         datePicker.SetScheme (new Scheme (
                                           new Attribute (
                                           new Attribute (
-                                                         SchemeManager.GetScheme (Schemes.Toplevel).Normal.Foreground.GetBrighterColor (),
-                                                         SchemeManager.GetScheme (Schemes.Toplevel).Normal.Background.GetBrighterColor (),
-                                                         SchemeManager.GetScheme (Schemes.Toplevel).Normal.Style)));
+                                                         SchemeManager.GetScheme (Schemes.Runnable).Normal.Foreground.GetBrighterColor (),
+                                                         SchemeManager.GetScheme (Schemes.Runnable).Normal.Background.GetBrighterColor (),
+                                                         SchemeManager.GetScheme (Schemes.Runnable).Normal.Style)));
 
 
         TransparentView transparentView = new ()
         TransparentView transparentView = new ()
         {
         {
@@ -237,7 +237,7 @@ public class Arrangement : Scenario
             Width = Dim.Auto (minimumContentDim: 15),
             Width = Dim.Auto (minimumContentDim: 15),
             Height = Dim.Auto (minimumContentDim: 3),
             Height = Dim.Auto (minimumContentDim: 3),
             Title = $"Overlapped{id} _{GetNextHotKey ()}",
             Title = $"Overlapped{id} _{GetNextHotKey ()}",
-            SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Toplevel),
+            SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Runnable),
             Id = $"Overlapped{id}",
             Id = $"Overlapped{id}",
             ShadowStyle = ShadowStyle.Transparent,
             ShadowStyle = ShadowStyle.Transparent,
             BorderStyle = LineStyle.Double,
             BorderStyle = LineStyle.Double,

+ 20 - 20
Examples/UICatalog/Scenarios/Bars.cs

@@ -14,9 +14,9 @@ public class Bars : Scenario
     public override void Main ()
     public override void Main ()
     {
     {
         Application.Init ();
         Application.Init ();
-        Toplevel app = new ();
+        Runnable app = new ();
 
 
-        app.Loaded += App_Loaded;
+        app.IsModalChanged += App_Loaded;
 
 
         Application.Run (app);
         Application.Run (app);
         app.Dispose ();
         app.Dispose ();
@@ -28,7 +28,7 @@ public class Bars : Scenario
     // QuitKey and it only sticks if changed after init
     // QuitKey and it only sticks if changed after init
     private void App_Loaded (object sender, EventArgs e)
     private void App_Loaded (object sender, EventArgs e)
     {
     {
-        Application.Current!.Title = GetQuitKeyAndName ();
+        Application.TopRunnableView!.Title = GetQuitKeyAndName ();
 
 
         ObservableCollection<string> eventSource = new ();
         ObservableCollection<string> eventSource = new ();
         ListView eventLog = new ListView ()
         ListView eventLog = new ListView ()
@@ -37,11 +37,11 @@ public class Bars : Scenario
             X = Pos.AnchorEnd (),
             X = Pos.AnchorEnd (),
             Width = Dim.Auto (),
             Width = Dim.Auto (),
             Height = Dim.Fill (), // Make room for some wide things
             Height = Dim.Fill (), // Make room for some wide things
-            SchemeName = "Toplevel",
+            SchemeName = "Runnable",
             Source = new ListWrapper<string> (eventSource)
             Source = new ListWrapper<string> (eventSource)
         };
         };
         eventLog.Border!.Thickness = new (0, 1, 0, 0);
         eventLog.Border!.Thickness = new (0, 1, 0, 0);
-        Application.Current.Add (eventLog);
+        Application.TopRunnableView.Add (eventLog);
 
 
         FrameView menuBarLikeExamples = new ()
         FrameView menuBarLikeExamples = new ()
         {
         {
@@ -51,7 +51,7 @@ public class Bars : Scenario
             Width = Dim.Fill () - Dim.Width (eventLog),
             Width = Dim.Fill () - Dim.Width (eventLog),
             Height = Dim.Percent(33),
             Height = Dim.Percent(33),
         };
         };
-        Application.Current.Add (menuBarLikeExamples);
+        Application.TopRunnableView.Add (menuBarLikeExamples);
 
 
         Label label = new Label ()
         Label label = new Label ()
         {
         {
@@ -80,7 +80,7 @@ public class Bars : Scenario
         };
         };
         menuBarLikeExamples.Add (label);
         menuBarLikeExamples.Add (label);
 
 
-        //bar = new MenuBarv2
+        //bar = new MenuBar
         //{
         //{
         //    Id = "menuBar",
         //    Id = "menuBar",
         //    X = Pos.Right (label),
         //    X = Pos.Right (label),
@@ -98,7 +98,7 @@ public class Bars : Scenario
             Width = Dim.Fill () - Dim.Width (eventLog),
             Width = Dim.Fill () - Dim.Width (eventLog),
             Height = Dim.Percent (33),
             Height = Dim.Percent (33),
         };
         };
-        Application.Current.Add (menuLikeExamples);
+        Application.TopRunnableView.Add (menuLikeExamples);
 
 
         label = new Label ()
         label = new Label ()
         {
         {
@@ -128,7 +128,7 @@ public class Bars : Scenario
         };
         };
         menuLikeExamples.Add (label);
         menuLikeExamples.Add (label);
 
 
-        bar = new Menuv2
+        bar = new Menu
         {
         {
             Id = "menu",
             Id = "menu",
             X = Pos.Left (label),
             X = Pos.Left (label),
@@ -147,7 +147,7 @@ public class Bars : Scenario
         };
         };
         menuLikeExamples.Add (label);
         menuLikeExamples.Add (label);
 
 
-        Menuv2 popOverMenu  = new Menuv2
+        Menu popOverMenu  = new Menu
         {
         {
             Id = "popupMenu",
             Id = "popupMenu",
             X = Pos.Left (label),
             X = Pos.Left (label),
@@ -212,7 +212,7 @@ public class Bars : Scenario
             Width = Dim.Width (menuLikeExamples),
             Width = Dim.Width (menuLikeExamples),
             Height = Dim.Percent (33),
             Height = Dim.Percent (33),
         };
         };
-        Application.Current.Add (statusBarLikeExamples);
+        Application.TopRunnableView.Add (statusBarLikeExamples);
 
 
         label = new Label ()
         label = new Label ()
         {
         {
@@ -249,7 +249,7 @@ public class Bars : Scenario
         ConfigStatusBar (bar);
         ConfigStatusBar (bar);
         statusBarLikeExamples.Add (bar);
         statusBarLikeExamples.Add (bar);
 
 
-        foreach (FrameView frameView in Application.Current.SubViews.Where (f => f is FrameView)!)
+        foreach (FrameView frameView in Application.TopRunnableView.SubViews.Where (f => f is FrameView)!)
         {
         {
             foreach (Bar barView in frameView.SubViews.Where (b => b is Bar)!)
             foreach (Bar barView in frameView.SubViews.Where (b => b is Bar)!)
             {
             {
@@ -269,8 +269,8 @@ public class Bars : Scenario
 
 
     //private void SetupContentMenu ()
     //private void SetupContentMenu ()
     //{
     //{
-    //    Application.Current.Add (new Label { Text = "Right Click for Context Menu", X = Pos.Center (), Y = 4 });
-    //    Application.Current.MouseClick += ShowContextMenu;
+    //    Application.TopRunnable.Add (new Label { Text = "Right Click for Context Menu", X = Pos.Center (), Y = 4 });
+    //    Application.TopRunnable.MouseClick += ShowContextMenu;
     //}
     //}
 
 
     //private void ShowContextMenu (object s, MouseEventEventArgs e)
     //private void ShowContextMenu (object s, MouseEventEventArgs e)
@@ -309,7 +309,7 @@ public class Bars : Scenario
     //                                                  new TimeSpan (0),
     //                                                  new TimeSpan (0),
     //                                                  () =>
     //                                                  () =>
     //                                                  {
     //                                                  {
-    //                                                      MessageBox.Query ("File", "New");
+    //                                                      MessageBox.Query (App, "File", "New");
 
 
     //                                                      return false;
     //                                                      return false;
     //                                                  });
     //                                                  });
@@ -331,7 +331,7 @@ public class Bars : Scenario
     //                                               new TimeSpan (0),
     //                                               new TimeSpan (0),
     //                                               () =>
     //                                               () =>
     //                                               {
     //                                               {
-    //                                                   MessageBox.Query ("File", "Open");
+    //                                                   MessageBox.Query (App, "File", "Open");
 
 
     //                                                   return false;
     //                                                   return false;
     //                                               });
     //                                               });
@@ -353,7 +353,7 @@ public class Bars : Scenario
     //                                               new TimeSpan (0),
     //                                               new TimeSpan (0),
     //                                               () =>
     //                                               () =>
     //                                               {
     //                                               {
-    //                                                   MessageBox.Query ("File", "Save");
+    //                                                   MessageBox.Query (App, "File", "Save");
 
 
     //                                                   return false;
     //                                                   return false;
     //                                               });
     //                                               });
@@ -375,7 +375,7 @@ public class Bars : Scenario
     //                                                 new TimeSpan (0),
     //                                                 new TimeSpan (0),
     //                                                 () =>
     //                                                 () =>
     //                                                 {
     //                                                 {
-    //                                                     MessageBox.Query ("File", "Save As");
+    //                                                     MessageBox.Query (App, "File", "Save As");
 
 
     //                                                     return false;
     //                                                     return false;
     //                                                 });
     //                                                 });
@@ -383,7 +383,7 @@ public class Bars : Scenario
 
 
     //    contextMenu.Add (newMenu, open, save, saveAs);
     //    contextMenu.Add (newMenu, open, save, saveAs);
 
 
-    //    contextMenu.KeyBindings.Add (Key.Esc, Command.QuitToplevel);
+    //    contextMenu.KeyBindings.Add (Key.Esc, Command.Quit);
 
 
     //    contextMenu.Initialized += Menu_Initialized;
     //    contextMenu.Initialized += Menu_Initialized;
 
 
@@ -555,7 +555,7 @@ public class Bars : Scenario
 
 
         return;
         return;
 
 
-        void Button_Clicked (object sender, EventArgs e) { MessageBox.Query ("Hi", $"You clicked {sender}"); }
+        void Button_Clicked (object sender, EventArgs e) { MessageBox.Query ((sender as View)?.App, "Hi", $"You clicked {sender}"); }
 
 
     }
     }
 
 

+ 5 - 5
Examples/UICatalog/Scenarios/Buttons.cs

@@ -59,7 +59,7 @@ public class Buttons : Scenario
 
 
                                     if (e.Handled)
                                     if (e.Handled)
                                     {
                                     {
-                                        MessageBox.ErrorQuery ("Error", "This button is no longer the Quit button; the Swap Default button is.", "_Ok");
+                                        MessageBox.ErrorQuery ((s as View)?.App, "Error", "This button is no longer the Quit button; the Swap Default button is.", "_Ok");
                                     }
                                     }
                                 };
                                 };
         main.Add (swapButton);
         main.Add (swapButton);
@@ -69,7 +69,7 @@ public class Buttons : Scenario
             button.Accepting += (s, e) =>
             button.Accepting += (s, e) =>
                              {
                              {
                                  string btnText = button.Text;
                                  string btnText = button.Text;
-                                 MessageBox.Query ("Message", $"Did you click {txt}?", "Yes", "No");
+                                 MessageBox.Query ((s as View)?.App, "Message", $"Did you click {txt}?", "Yes", "No");
                                  e.Handled = true;
                                  e.Handled = true;
                              };
                              };
         }
         }
@@ -112,7 +112,7 @@ public class Buttons : Scenario
                  );
                  );
         button.Accepting += (s, e) =>
         button.Accepting += (s, e) =>
                          {
                          {
-                             MessageBox.Query ("Message", "Question?", "Yes", "No");
+                             MessageBox.Query ((s as View)?.App, "Message", "Question?", "Yes", "No");
                              e.Handled = true;
                              e.Handled = true;
                          };
                          };
 
 
@@ -294,7 +294,7 @@ public class Buttons : Scenario
             X = 2,
             X = 2,
             Y = Pos.Bottom (osAlignment) + 1,
             Y = Pos.Bottom (osAlignment) + 1,
             Width = Dim.Width (computedFrame) - 2,
             Width = Dim.Width (computedFrame) - 2,
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             Text = mhkb
             Text = mhkb
         };
         };
         moveHotKeyBtn.Accepting += (s, e) =>
         moveHotKeyBtn.Accepting += (s, e) =>
@@ -311,7 +311,7 @@ public class Buttons : Scenario
             X = Pos.Left (absoluteFrame) + 1,
             X = Pos.Left (absoluteFrame) + 1,
             Y = Pos.Bottom (osAlignment) + 1,
             Y = Pos.Bottom (osAlignment) + 1,
             Width = Dim.Width (absoluteFrame) - 2,
             Width = Dim.Width (absoluteFrame) - 2,
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             Text = muhkb
             Text = muhkb
         };
         };
         moveUnicodeHotKeyBtn.Accepting += (s, e) =>
         moveUnicodeHotKeyBtn.Accepting += (s, e) =>

+ 5 - 5
Examples/UICatalog/Scenarios/CharacterMap/CharacterMap.cs

@@ -176,13 +176,13 @@ public class CharacterMap : Scenario
 
 
         top.Add (_categoryList);
         top.Add (_categoryList);
 
 
-        var menu = new MenuBarv2
+        var menu = new MenuBar
         {
         {
             Menus =
             Menus =
             [
             [
                 new (
                 new (
                      "_File",
                      "_File",
-                     new MenuItemv2 []
+                     new MenuItem []
                      {
                      {
                          new (
                          new (
                               "_Quit",
                               "_Quit",
@@ -337,14 +337,14 @@ public class CharacterMap : Scenario
                    );
                    );
     }
     }
 
 
-    private MenuItemv2 CreateMenuShowWidth ()
+    private MenuItem CreateMenuShowWidth ()
     {
     {
         CheckBox cb = new ()
         CheckBox cb = new ()
         {
         {
             Title = "_Show Glyph Width",
             Title = "_Show Glyph Width",
             CheckedState = _charMap!.ShowGlyphWidths ? CheckState.Checked : CheckState.None
             CheckedState = _charMap!.ShowGlyphWidths ? CheckState.Checked : CheckState.None
         };
         };
-        var item = new MenuItemv2 { CommandView = cb };
+        var item = new MenuItem { CommandView = cb };
 
 
         item.Action += () =>
         item.Action += () =>
                        {
                        {
@@ -357,7 +357,7 @@ public class CharacterMap : Scenario
         return item;
         return item;
     }
     }
 
 
-    private MenuItemv2 CreateMenuUnicodeCategorySelector ()
+    private MenuItem CreateMenuUnicodeCategorySelector ()
     {
     {
         // First option is "All" (no filter), followed by all UnicodeCategory names
         // First option is "All" (no filter), followed by all UnicodeCategory names
         string [] allCategoryNames = Enum.GetNames<UnicodeCategory> ();
         string [] allCategoryNames = Enum.GetNames<UnicodeCategory> ();

+ 3 - 2
Examples/UICatalog/Scenarios/ChineseUI.cs

@@ -32,8 +32,9 @@ public class ChineseUI : Scenario
 
 
         btn.Accepting += (s, e) =>
         btn.Accepting += (s, e) =>
                       {
                       {
-                          int result = MessageBox.Query (
-                                                         "Confirm",
+                          int? result = MessageBox.Query (
+                                                          (s as View)?.App,
+                                                          "Confirm",
                                                          "Are you sure you want to quit ui?",
                                                          "Are you sure you want to quit ui?",
                                                          0,
                                                          0,
                                                          "Yes",
                                                          "Yes",

+ 210 - 188
Examples/UICatalog/Scenarios/ClassExplorer.cs

@@ -1,6 +1,5 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
+#nullable enable
+
 using System.Reflection;
 using System.Reflection;
 using System.Text;
 using System.Text;
 
 
@@ -11,63 +10,45 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("TreeView")]
 [ScenarioCategory ("TreeView")]
 public class ClassExplorer : Scenario
 public class ClassExplorer : Scenario
 {
 {
-    private MenuItem _highlightModelTextOnly;
-    private MenuItem _miShowPrivate;
-    private TextView _textView;
-    private TreeView<object> _treeView;
+    private CheckBox? _highlightModelTextOnlyCheckBox;
+    private CheckBox? _showPrivateCheckBox;
+    private TextView? _textView;
+    private TreeView<object>? _treeView;
 
 
     public override void Main ()
     public override void Main ()
     {
     {
         Application.Init ();
         Application.Init ();
-        var top = new Toplevel ();
 
 
-        var menu = new MenuBar
+        Window win = new ()
         {
         {
-            Menus =
-            [
-                new MenuBarItem ("_File", new MenuItem [] { new ("_Quit", "", () => Quit ()) }),
-                new MenuBarItem (
-                                 "_View",
-                                 new []
-                                 {
-                                     _miShowPrivate =
-                                         new MenuItem (
-                                                       "_Include Private",
-                                                       "",
-                                                       () => ShowPrivate ()
-                                                      ) { Checked = false, CheckType = MenuItemCheckStyle.Checked },
-                                     new ("_Expand All", "", () => _treeView.ExpandAll ()),
-                                     new ("_Collapse All", "", () => _treeView.CollapseAll ())
-                                 }
-                                ),
-                new MenuBarItem (
-                                 "_Style",
-                                 new []
-                                 {
-                                     _highlightModelTextOnly = new MenuItem (
-                                                                             "_Highlight Model Text Only",
-                                                                             "",
-                                                                             () => OnCheckHighlightModelTextOnly ()
-                                                                            ) { CheckType = MenuItemCheckStyle.Checked }
-                                 }
-                                )
-            ]
+            Title = GetName (),
+            BorderStyle = LineStyle.None
         };
         };
-        top.Add (menu);
 
 
-        var win = new Window
+        // MenuBar
+        MenuBar menuBar = new ();
+
+        // Search controls
+        Label lblSearch = new ()
         {
         {
-            Title = GetName (),
-            Y = Pos.Bottom (menu)
+            Y = Pos.Bottom (menuBar),
+            Title = "Search:"
         };
         };
 
 
-        _treeView = new TreeView<object> { X = 0, Y = 1, Width = Dim.Percent (50), Height = Dim.Fill () };
-
-        var lblSearch = new Label { Text = "Search" };
-        var tfSearch = new TextField { Width = 20, X = Pos.Right (lblSearch) };
+        TextField tfSearch = new ()
+        {
+            Y = Pos.Top (lblSearch),
+            X = Pos.Right (lblSearch) + 1,
+            Width = 20
+        };
 
 
-        win.Add (lblSearch);
-        win.Add (tfSearch);
+        // TreeView
+        _treeView = new ()
+        {
+            Y = Pos.Bottom (lblSearch),
+            Width = Dim.Percent (50),
+            Height = Dim.Fill ()
+        };
 
 
         TreeViewTextFilter<object> filter = new (_treeView);
         TreeViewTextFilter<object> filter = new (_treeView);
         _treeView.Filter = filter;
         _treeView.Filter = filter;
@@ -76,7 +57,7 @@ public class ClassExplorer : Scenario
                                 {
                                 {
                                     filter.Text = tfSearch.Text;
                                     filter.Text = tfSearch.Text;
 
 
-                                    if (_treeView.SelectedObject != null)
+                                    if (_treeView.SelectedObject is { })
                                     {
                                     {
                                         _treeView.EnsureVisible (_treeView.SelectedObject);
                                         _treeView.EnsureVisible (_treeView.SelectedObject);
                                     }
                                     }
@@ -87,111 +68,146 @@ public class ClassExplorer : Scenario
         _treeView.TreeBuilder = new DelegateTreeBuilder<object> (ChildGetter, CanExpand);
         _treeView.TreeBuilder = new DelegateTreeBuilder<object> (ChildGetter, CanExpand);
         _treeView.SelectionChanged += TreeView_SelectionChanged;
         _treeView.SelectionChanged += TreeView_SelectionChanged;
 
 
-        win.Add (_treeView);
-
-        _textView = new TextView { X = Pos.Right (_treeView), Y = 0, Width = Dim.Fill (), Height = Dim.Fill () };
-
-        win.Add (_textView);
+        // TextView for details
+        _textView = new ()
+        {
+            X = Pos.Right (_treeView),
+            Y = Pos.Top (_treeView),
+            Width = Dim.Fill (),
+            Height = Dim.Fill (),
+            ReadOnly = true,
+        };
 
 
-        top.Add (win);
+        // Menu setup
+        _showPrivateCheckBox = new ()
+        {
+            Title = "_Include Private"
+        };
+        _showPrivateCheckBox.CheckedStateChanged += (s, e) => ShowPrivate ();
 
 
-        Application.Run (top);
-        top.Dispose ();
+        _highlightModelTextOnlyCheckBox = new ()
+        {
+            Title = "_Highlight Model Text Only"
+        };
+        _highlightModelTextOnlyCheckBox.CheckedStateChanged += (s, e) => OnCheckHighlightModelTextOnly ();
+
+        menuBar.Add (
+                     new MenuBarItem (
+                                      "_File",
+                                      [
+                                          new MenuItem
+                                          {
+                                              Title = "_Quit",
+                                              Action = Quit
+                                          }
+                                      ]
+                                     )
+                    );
+
+        menuBar.Add (
+                     new MenuBarItem (
+                                      "_View",
+                                      [
+                                          new MenuItem
+                                          {
+                                              CommandView = _showPrivateCheckBox
+                                          },
+                                          new MenuItem
+                                          {
+                                              Title = "_Expand All",
+                                              Action = () => _treeView?.ExpandAll ()
+                                          },
+                                          new MenuItem
+                                          {
+                                              Title = "_Collapse All",
+                                              Action = () => _treeView?.CollapseAll ()
+                                          }
+                                      ]
+                                     )
+                    );
+
+        menuBar.Add (
+                     new MenuBarItem (
+                                      "_Style",
+                                      [
+                                          new MenuItem
+                                          {
+                                              CommandView = _highlightModelTextOnlyCheckBox
+                                          }
+                                      ]
+                                     )
+                    );
+
+        // Add views in order of visual appearance
+        win.Add (menuBar, lblSearch, tfSearch, _treeView, _textView);
+
+        Application.Run (win);
+        win.Dispose ();
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
-    private bool CanExpand (object arg) { return arg is Assembly || arg is Type || arg is ShowForType; }
+    private bool CanExpand (object arg) => arg is Assembly or Type or ShowForType;
 
 
     private IEnumerable<object> ChildGetter (object arg)
     private IEnumerable<object> ChildGetter (object arg)
     {
     {
         try
         try
         {
         {
-            if (arg is Assembly a)
-            {
-                return a.GetTypes ();
-            }
-
-            if (arg is Type t)
-            {
-                // Note that here we cannot simply return the enum values as the same object cannot appear under multiple branches
-                return Enum.GetValues (typeof (Showable))
-                           .Cast<Showable> ()
-
-                           // Although we new the Type every time the delegate is called state is preserved because the class has appropriate equality members
-                           .Select (v => new ShowForType (v, t));
-            }
-
-            if (arg is ShowForType show)
-            {
-                switch (show.ToShow)
-                {
-                    case Showable.Properties:
-                        return show.Type.GetProperties (GetFlags ());
-                    case Showable.Constructors:
-                        return show.Type.GetConstructors (GetFlags ());
-                    case Showable.Events:
-                        return show.Type.GetEvents (GetFlags ());
-                    case Showable.Fields:
-                        return show.Type.GetFields (GetFlags ());
-                    case Showable.Methods:
-                        return show.Type.GetMethods (GetFlags ());
-                }
-            }
+            return arg switch
+                   {
+                       Assembly assembly => assembly.GetTypes (),
+                       Type type => Enum.GetValues (typeof (Showable))
+                                        .Cast<Showable> ()
+                                        .Select (v => new ShowForType (v, type)),
+                       ShowForType show => show.ToShow switch
+                                           {
+                                               Showable.Properties => show.Type.GetProperties (GetFlags ()),
+                                               Showable.Constructors => show.Type.GetConstructors (GetFlags ()),
+                                               Showable.Events => show.Type.GetEvents (GetFlags ()),
+                                               Showable.Fields => show.Type.GetFields (GetFlags ()),
+                                               Showable.Methods => show.Type.GetMethods (GetFlags ()),
+                                               _ => Enumerable.Empty<object> ()
+                                           },
+                       _ => Enumerable.Empty<object> ()
+                   };
         }
         }
         catch (Exception)
         catch (Exception)
         {
         {
             return Enumerable.Empty<object> ();
             return Enumerable.Empty<object> ();
         }
         }
-
-        return Enumerable.Empty<object> ();
     }
     }
 
 
-    private BindingFlags GetFlags ()
-    {
-        if (_miShowPrivate.Checked == true)
-        {
-            return BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
-        }
-
-        return BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
-    }
+    private BindingFlags GetFlags () =>
+        _showPrivateCheckBox?.CheckedState == CheckState.Checked
+            ? BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic
+            : BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
 
 
     private string GetRepresentation (object model)
     private string GetRepresentation (object model)
     {
     {
         try
         try
         {
         {
-            if (model is Assembly ass)
-            {
-                return ass.GetName ().Name;
-            }
-
-            if (model is PropertyInfo p)
-            {
-                return p.Name;
-            }
-
-            if (model is FieldInfo f)
-            {
-                return f.Name;
-            }
-
-            if (model is EventInfo ei)
-            {
-                return ei.Name;
-            }
+            return model switch
+                   {
+                       Assembly assembly => assembly.GetName ().Name ?? string.Empty,
+                       PropertyInfo propertyInfo => propertyInfo.Name,
+                       FieldInfo fieldInfo => fieldInfo.Name,
+                       EventInfo eventInfo => eventInfo.Name,
+                       _ => model.ToString () ?? string.Empty
+                   };
         }
         }
         catch (Exception ex)
         catch (Exception ex)
         {
         {
             return ex.Message;
             return ex.Message;
         }
         }
-
-        return model.ToString ();
     }
     }
 
 
     private void OnCheckHighlightModelTextOnly ()
     private void OnCheckHighlightModelTextOnly ()
     {
     {
-        _treeView.Style.HighlightModelTextOnly = !_treeView.Style.HighlightModelTextOnly;
-        _highlightModelTextOnly.Checked = _treeView.Style.HighlightModelTextOnly;
+        if (_treeView is null)
+        {
+            return;
+        }
+
+        _treeView.Style.HighlightModelTextOnly = _highlightModelTextOnlyCheckBox?.CheckedState == CheckState.Checked;
         _treeView.SetNeedsDraw ();
         _treeView.SetNeedsDraw ();
     }
     }
 
 
@@ -199,17 +215,21 @@ public class ClassExplorer : Scenario
 
 
     private void ShowPrivate ()
     private void ShowPrivate ()
     {
     {
-        _miShowPrivate.Checked = !_miShowPrivate.Checked;
-        _treeView.RebuildTree ();
-        _treeView.SetFocus ();
+        _treeView?.RebuildTree ();
+        _treeView?.SetFocus ();
     }
     }
 
 
-    private void TreeView_SelectionChanged (object sender, SelectionChangedEventArgs<object> e)
+    private void TreeView_SelectionChanged (object? sender, SelectionChangedEventArgs<object> e)
     {
     {
-        object val = e.NewValue;
+        if (_treeView is null || _textView is null)
+        {
+            return;
+        }
+
+        object? val = e.NewValue;
         object [] all = _treeView.GetAllSelectedObjects ().ToArray ();
         object [] all = _treeView.GetAllSelectedObjects ().ToArray ();
 
 
-        if (val == null || val is ShowForType)
+        if (val is null or ShowForType)
         {
         {
             return;
             return;
         }
         }
@@ -218,69 +238,73 @@ public class ClassExplorer : Scenario
         {
         {
             if (all.Length > 1)
             if (all.Length > 1)
             {
             {
-                _textView.Text = all.Length + " Objects";
+                _textView.Text = $"{all.Length} Objects";
             }
             }
             else
             else
             {
             {
-                var sb = new StringBuilder ();
+                StringBuilder sb = new ();
 
 
-                // tell the user about the currently selected tree node
-                sb.AppendLine (e.NewValue.GetType ().Name);
+                sb.AppendLine (e.NewValue?.GetType ().Name ?? string.Empty);
 
 
-                if (val is Assembly ass)
+                switch (val)
                 {
                 {
-                    sb.AppendLine ($"Location:{ass.Location}");
-                    sb.AppendLine ($"FullName:{ass.FullName}");
-                }
+                    case Assembly assembly:
+                        sb.AppendLine ($"Location:{assembly.Location}");
+                        sb.AppendLine ($"FullName:{assembly.FullName}");
 
 
-                if (val is PropertyInfo p)
-                {
-                    sb.AppendLine ($"Name:{p.Name}");
-                    sb.AppendLine ($"Type:{p.PropertyType}");
-                    sb.AppendLine ($"CanWrite:{p.CanWrite}");
-                    sb.AppendLine ($"CanRead:{p.CanRead}");
-                }
+                        break;
 
 
-                if (val is FieldInfo f)
-                {
-                    sb.AppendLine ($"Name:{f.Name}");
-                    sb.AppendLine ($"Type:{f.FieldType}");
-                }
+                    case PropertyInfo propertyInfo:
+                        sb.AppendLine ($"Name:{propertyInfo.Name}");
+                        sb.AppendLine ($"Type:{propertyInfo.PropertyType}");
+                        sb.AppendLine ($"CanWrite:{propertyInfo.CanWrite}");
+                        sb.AppendLine ($"CanRead:{propertyInfo.CanRead}");
 
 
-                if (val is EventInfo ev)
-                {
-                    sb.AppendLine ($"Name:{ev.Name}");
-                    sb.AppendLine ("Parameters:");
-
-                    foreach (ParameterInfo parameter in ev.EventHandlerType.GetMethod ("Invoke")
-                                                          .GetParameters ())
-                    {
-                        sb.AppendLine ($"  {parameter.ParameterType} {parameter.Name}");
-                    }
-                }
+                        break;
 
 
-                if (val is MethodInfo method)
-                {
-                    sb.AppendLine ($"Name:{method.Name}");
-                    sb.AppendLine ($"IsPublic:{method.IsPublic}");
-                    sb.AppendLine ($"IsStatic:{method.IsStatic}");
-                    sb.AppendLine ($"Parameters:{(method.GetParameters ().Any () ? "" : "None")}");
-
-                    foreach (ParameterInfo parameter in method.GetParameters ())
-                    {
-                        sb.AppendLine ($"  {parameter.ParameterType} {parameter.Name}");
-                    }
-                }
+                    case FieldInfo fieldInfo:
+                        sb.AppendLine ($"Name:{fieldInfo.Name}");
+                        sb.AppendLine ($"Type:{fieldInfo.FieldType}");
 
 
-                if (val is ConstructorInfo ctor)
-                {
-                    sb.AppendLine ($"Name:{ctor.Name}");
-                    sb.AppendLine ($"Parameters:{(ctor.GetParameters ().Any () ? "" : "None")}");
+                        break;
+
+                    case EventInfo eventInfo:
+                        sb.AppendLine ($"Name:{eventInfo.Name}");
+                        sb.AppendLine ("Parameters:");
+
+                        if (eventInfo.EventHandlerType?.GetMethod ("Invoke") is { } invokeMethod)
+                        {
+                            foreach (ParameterInfo parameter in invokeMethod.GetParameters ())
+                            {
+                                sb.AppendLine ($"  {parameter.ParameterType} {parameter.Name}");
+                            }
+                        }
 
 
-                    foreach (ParameterInfo parameter in ctor.GetParameters ())
-                    {
-                        sb.AppendLine ($"  {parameter.ParameterType} {parameter.Name}");
-                    }
+                        break;
+
+                    case MethodInfo methodInfo:
+                        sb.AppendLine ($"Name:{methodInfo.Name}");
+                        sb.AppendLine ($"IsPublic:{methodInfo.IsPublic}");
+                        sb.AppendLine ($"IsStatic:{methodInfo.IsStatic}");
+                        sb.AppendLine ($"Parameters:{(methodInfo.GetParameters ().Length > 0 ? string.Empty : "None")}");
+
+                        foreach (ParameterInfo parameter in methodInfo.GetParameters ())
+                        {
+                            sb.AppendLine ($"  {parameter.ParameterType} {parameter.Name}");
+                        }
+
+                        break;
+
+                    case ConstructorInfo constructorInfo:
+                        sb.AppendLine ($"Name:{constructorInfo.Name}");
+                        sb.AppendLine ($"Parameters:{(constructorInfo.GetParameters ().Length > 0 ? string.Empty : "None")}");
+
+                        foreach (ParameterInfo parameter in constructorInfo.GetParameters ())
+                        {
+                            sb.AppendLine ($"  {parameter.ParameterType} {parameter.Name}");
+                        }
+
+                        break;
                 }
                 }
 
 
                 _textView.Text = sb.ToString ().Replace ("\r\n", "\n");
                 _textView.Text = sb.ToString ().Replace ("\r\n", "\n");
@@ -303,7 +327,7 @@ public class ClassExplorer : Scenario
         Methods
         Methods
     }
     }
 
 
-    private class ShowForType
+    private sealed class ShowForType
     {
     {
         public ShowForType (Showable toShow, Type type)
         public ShowForType (Showable toShow, Type type)
         {
         {
@@ -314,13 +338,11 @@ public class ClassExplorer : Scenario
         public Showable ToShow { get; }
         public Showable ToShow { get; }
         public Type Type { get; }
         public Type Type { get; }
 
 
-        // Make sure to implement Equals methods on your objects if you intend to return new instances every time in ChildGetter
-        public override bool Equals (object obj)
-        {
-            return obj is ShowForType type && EqualityComparer<Type>.Default.Equals (Type, type.Type) && ToShow == type.ToShow;
-        }
+        public override bool Equals (object? obj) =>
+            obj is ShowForType type && EqualityComparer<Type>.Default.Equals (Type, type.Type) && ToShow == type.ToShow;
+
+        public override int GetHashCode () => HashCode.Combine (Type, ToShow);
 
 
-        public override int GetHashCode () { return HashCode.Combine (Type, ToShow); }
-        public override string ToString () { return ToShow.ToString (); }
+        public override string ToString () => ToShow.ToString ();
     }
     }
 }
 }

+ 1 - 1
Examples/UICatalog/Scenarios/Clipping.cs

@@ -118,7 +118,7 @@ public class Clipping : Scenario
             Height = Dim.Auto (minimumContentDim: 4),
             Height = Dim.Auto (minimumContentDim: 4),
             Width = Dim.Auto (minimumContentDim: 14),
             Width = Dim.Auto (minimumContentDim: 14),
             Title = $"Overlapped{id} _{GetNextHotKey ()}",
             Title = $"Overlapped{id} _{GetNextHotKey ()}",
-            SchemeName = SchemeManager.SchemesToSchemeName(Schemes.Toplevel),
+            SchemeName = SchemeManager.SchemesToSchemeName(Schemes.Runnable),
             Id = $"Overlapped{id}",
             Id = $"Overlapped{id}",
             ShadowStyle = ShadowStyle.Transparent,
             ShadowStyle = ShadowStyle.Transparent,
             BorderStyle = LineStyle.Double,
             BorderStyle = LineStyle.Double,

+ 169 - 112
Examples/UICatalog/Scenarios/CollectionNavigatorTester.cs

@@ -1,14 +1,13 @@
-using System;
-using System.Collections.Generic;
+#nullable enable
+
 using System.Collections.ObjectModel;
 using System.Collections.ObjectModel;
-using System.Linq;
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
 
 
 [ScenarioMetadata (
 [ScenarioMetadata (
-                               "Collection Navigator",
-                               "Demonstrates keyboard navigation in ListView & TreeView (CollectionNavigator)."
-                           )]
+                      "Collection Navigator",
+                      "Demonstrates keyboard navigation in ListView & TreeView (CollectionNavigator)."
+                  )]
 [ScenarioCategory ("Controls")]
 [ScenarioCategory ("Controls")]
 [ScenarioCategory ("ListView")]
 [ScenarioCategory ("ListView")]
 [ScenarioCategory ("TreeView")]
 [ScenarioCategory ("TreeView")]
@@ -16,120 +15,165 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("Mouse and Keyboard")]
 [ScenarioCategory ("Mouse and Keyboard")]
 public class CollectionNavigatorTester : Scenario
 public class CollectionNavigatorTester : Scenario
 {
 {
-    private ObservableCollection<string> _items = new ObservableCollection<string> (new ObservableCollection<string> ()
-    {
-        "a",
-        "b",
-        "bb",
-        "c",
-        "ccc",
-        "ccc",
-        "cccc",
-        "ddd",
-        "dddd",
-        "dddd",
-        "ddddd",
-        "dddddd",
-        "ddddddd",
-        "this",
-        "this is a test",
-        "this was a test",
-        "this and",
-        "that and that",
-        "the",
-        "think",
-        "thunk",
-        "thunks",
-        "zip",
-        "zap",
-        "zoo",
-        "@jack",
-        "@sign",
-        "@at",
-        "@ateme",
-        "n@",
-        "n@brown",
-        ".net",
-        "$100.00",
-        "$101.00",
-        "$101.10",
-        "$101.11",
-        "$200.00",
-        "$210.99",
-        "$$",
-        "apricot",
-        "arm",
-        "丗丙业丞",
-        "丗丙丛",
-        "text",
-        "egg",
-        "candle",
-        " <- space",
-        "\t<- tab",
-        "\n<- newline",
-        "\r<- formfeed",
-        "q",
-        "quit",
-        "quitter"
-    }.ToList ());
-
-    private Toplevel top;
-    private ListView _listView;
-    private TreeView _treeView;
-
-    // Don't create a Window, just return the top-level view
+    private ObservableCollection<string> _items = new (
+                                                       [
+                                                           "a",
+                                                           "b",
+                                                           "bb",
+                                                           "c",
+                                                           "ccc",
+                                                           "ccc",
+                                                           "cccc",
+                                                           "ddd",
+                                                           "dddd",
+                                                           "dddd",
+                                                           "ddddd",
+                                                           "dddddd",
+                                                           "ddddddd",
+                                                           "this",
+                                                           "this is a test",
+                                                           "this was a test",
+                                                           "this and",
+                                                           "that and that",
+                                                           "the",
+                                                           "think",
+                                                           "thunk",
+                                                           "thunks",
+                                                           "zip",
+                                                           "zap",
+                                                           "zoo",
+                                                           "@jack",
+                                                           "@sign",
+                                                           "@at",
+                                                           "@ateme",
+                                                           "n@",
+                                                           "n@brown",
+                                                           ".net",
+                                                           "$100.00",
+                                                           "$101.00",
+                                                           "$101.10",
+                                                           "$101.11",
+                                                           "$200.00",
+                                                           "$210.99",
+                                                           "$$",
+                                                           "apricot",
+                                                           "arm",
+                                                           "丗丙业丞",
+                                                           "丗丙丛",
+                                                           "text",
+                                                           "egg",
+                                                           "candle",
+                                                           " <- space",
+                                                           "\t<- tab",
+                                                           "\n<- newline",
+                                                           "\r<- formfeed",
+                                                           "q",
+                                                           "quit",
+                                                           "quitter"
+                                                       ]
+                                                      );
+
+    private Window? _top;
+    private ListView? _listView;
+    private TreeView? _treeView;
+    private CheckBox? _allowMarkingCheckBox;
+    private CheckBox? _allowMultiSelectionCheckBox;
+
     public override void Main ()
     public override void Main ()
     {
     {
         Application.Init ();
         Application.Init ();
-        top = new Toplevel { SchemeName = "Base" };
 
 
-        var allowMarking = new MenuItem ("Allow _Marking", "", null)
+        Window top = new ()
         {
         {
-            CheckType = MenuItemCheckStyle.Checked, Checked = false
+            SchemeName = "Base"
         };
         };
-        allowMarking.Action = () => allowMarking.Checked = _listView.AllowsMarking = !_listView.AllowsMarking;
+        _top = top;
+
+        // MenuBar
+        MenuBar menu = new ();
 
 
-        var allowMultiSelection = new MenuItem ("Allow Multi _Selection", "", null)
+        _allowMarkingCheckBox = new ()
         {
         {
-            CheckType = MenuItemCheckStyle.Checked, Checked = false
+            Title = "Allow _Marking"
         };
         };
 
 
-        allowMultiSelection.Action = () =>
-                                         allowMultiSelection.Checked =
-                                             _listView.AllowsMultipleSelection = !_listView.AllowsMultipleSelection;
-        allowMultiSelection.CanExecute = () => (bool)allowMarking.Checked;
+        _allowMarkingCheckBox.CheckedStateChanged += (s, e) =>
+                                                     {
+                                                         if (_listView is { })
+                                                         {
+                                                             _listView.AllowsMarking = _allowMarkingCheckBox.CheckedState == CheckState.Checked;
+                                                         }
 
 
-        var menu = new MenuBar
+                                                         if (_allowMultiSelectionCheckBox is { })
+                                                         {
+                                                             _allowMultiSelectionCheckBox.Enabled = _allowMarkingCheckBox.CheckedState == CheckState.Checked;
+                                                         }
+                                                     };
+
+        _allowMultiSelectionCheckBox = new ()
         {
         {
-            Menus =
-            [
-                new MenuBarItem (
-                                 "_Configure",
-                                 new []
-                                 {
-                                     allowMarking,
-                                     allowMultiSelection,
-                                     null,
-                                     new (
-                                          "_Quit",
-                                          $"{Application.QuitKey}",
-                                          () => Quit (),
-                                          null,
-                                          null,
-                                          (KeyCode)Application.QuitKey
-                                         )
-                                 }
-                                ),
-                new MenuBarItem ("_Quit", $"{Application.QuitKey}", () => Quit ())
-            ]
+            Title = "Allow Multi _Selection",
+            Enabled = false
         };
         };
 
 
+        _allowMultiSelectionCheckBox.CheckedStateChanged += (s, e) =>
+                                                            {
+                                                                if (_listView is { })
+                                                                {
+                                                                    _listView.AllowsMultipleSelection =
+                                                                        _allowMultiSelectionCheckBox.CheckedState == CheckState.Checked;
+                                                                }
+                                                            };
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_Configure",
+                                   [
+                                       new MenuItem
+                                       {
+                                           CommandView = _allowMarkingCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _allowMultiSelectionCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Key = Application.QuitKey,
+                                           Action = Quit
+                                       }
+                                   ]
+                                  )
+                 );
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_Quit",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Key = Application.QuitKey,
+                                           Action = Quit
+                                       }
+                                   ]
+                                  )
+                 );
+
         top.Add (menu);
         top.Add (menu);
 
 
         _items = new (_items.OrderBy (i => i, StringComparer.OrdinalIgnoreCase));
         _items = new (_items.OrderBy (i => i, StringComparer.OrdinalIgnoreCase));
 
 
         CreateListView ();
         CreateListView ();
-        var vsep = new Line { Orientation = Orientation.Vertical, X = Pos.Right (_listView), Y = 1, Height = Dim.Fill () };
+
+        Line vsep = new ()
+        {
+            Orientation = Orientation.Vertical,
+            X = Pos.Right (_listView!),
+            Y = 1,
+            Height = Dim.Fill ()
+        };
         top.Add (vsep);
         top.Add (vsep);
         CreateTreeView ();
         CreateTreeView ();
 
 
@@ -140,7 +184,12 @@ public class CollectionNavigatorTester : Scenario
 
 
     private void CreateListView ()
     private void CreateListView ()
     {
     {
-        var label = new Label
+        if (_top is null)
+        {
+            return;
+        }
+
+        Label label = new ()
         {
         {
             Text = "ListView",
             Text = "ListView",
             TextAlignment = Alignment.Center,
             TextAlignment = Alignment.Center,
@@ -149,9 +198,9 @@ public class CollectionNavigatorTester : Scenario
             Width = Dim.Percent (50),
             Width = Dim.Percent (50),
             Height = 1
             Height = 1
         };
         };
-        top.Add (label);
+        _top.Add (label);
 
 
-        _listView = new ListView
+        _listView = new ()
         {
         {
             X = 0,
             X = 0,
             Y = Pos.Bottom (label),
             Y = Pos.Bottom (label),
@@ -160,7 +209,7 @@ public class CollectionNavigatorTester : Scenario
             AllowsMarking = false,
             AllowsMarking = false,
             AllowsMultipleSelection = false
             AllowsMultipleSelection = false
         };
         };
-        top.Add (_listView);
+        _top.Add (_listView);
 
 
         _listView.SetSource (_items);
         _listView.SetSource (_items);
 
 
@@ -169,7 +218,12 @@ public class CollectionNavigatorTester : Scenario
 
 
     private void CreateTreeView ()
     private void CreateTreeView ()
     {
     {
-        var label = new Label
+        if (_top is null || _listView is null)
+        {
+            return;
+        }
+
+        Label label = new ()
         {
         {
             Text = "TreeView",
             Text = "TreeView",
             TextAlignment = Alignment.Center,
             TextAlignment = Alignment.Center,
@@ -178,23 +232,26 @@ public class CollectionNavigatorTester : Scenario
             Width = Dim.Percent (50),
             Width = Dim.Percent (50),
             Height = 1
             Height = 1
         };
         };
-        top.Add (label);
+        _top.Add (label);
 
 
-        _treeView = new TreeView
+        _treeView = new ()
         {
         {
-            X = Pos.Right (_listView) + 1, Y = Pos.Bottom (label), Width = Dim.Fill (), Height = Dim.Fill ()
+            X = Pos.Right (_listView) + 1,
+            Y = Pos.Bottom (label),
+            Width = Dim.Fill (),
+            Height = Dim.Fill ()
         };
         };
         _treeView.Style.HighlightModelTextOnly = true;
         _treeView.Style.HighlightModelTextOnly = true;
-        top.Add (_treeView);
+        _top.Add (_treeView);
 
 
-        var root = new TreeNode ("IsLetterOrDigit examples");
+        TreeNode root = new ("IsLetterOrDigit examples");
 
 
         root.Children = _items.Where (i => char.IsLetterOrDigit (i [0]))
         root.Children = _items.Where (i => char.IsLetterOrDigit (i [0]))
                               .Select (i => new TreeNode (i))
                               .Select (i => new TreeNode (i))
                               .Cast<ITreeNode> ()
                               .Cast<ITreeNode> ()
                               .ToList ();
                               .ToList ();
         _treeView.AddObject (root);
         _treeView.AddObject (root);
-        root = new TreeNode ("Non-IsLetterOrDigit examples");
+        root = new ("Non-IsLetterOrDigit examples");
 
 
         root.Children = _items.Where (i => !char.IsLetterOrDigit (i [0]))
         root.Children = _items.Where (i => !char.IsLetterOrDigit (i [0]))
                               .Select (i => new TreeNode (i))
                               .Select (i => new TreeNode (i))

+ 28 - 1
Examples/UICatalog/Scenarios/ColorPicker.cs

@@ -3,7 +3,7 @@ using System.Collections.Generic;
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
 
 
-[ScenarioMetadata ("ColorPicker", "Color Picker.")]
+[ScenarioMetadata ("ColorPicker", "Color Picker and TrueColor demonstration.")]
 [ScenarioCategory ("Colors")]
 [ScenarioCategory ("Colors")]
 [ScenarioCategory ("Controls")]
 [ScenarioCategory ("Controls")]
 public class ColorPickers : Scenario
 public class ColorPickers : Scenario
@@ -220,6 +220,33 @@ public class ColorPickers : Scenario
                                            };
                                            };
         app.Add (cbShowName);
         app.Add (cbShowName);
 
 
+        var lblDriverName = new Label
+        {
+            Y = Pos.Bottom (cbShowName) + 1, Text = $"Driver is `{Application.Driver?.GetName ()}`:"
+        };
+        bool canTrueColor = Application.Driver?.SupportsTrueColor ?? false;
+
+        var cbSupportsTrueColor = new CheckBox
+        {
+            X = Pos.Right (lblDriverName) + 1,
+            Y = Pos.Top (lblDriverName),
+            CheckedState = canTrueColor ? CheckState.Checked : CheckState.UnChecked,
+            CanFocus = false,
+            Enabled = false,
+            Text = "SupportsTrueColor"
+        };
+        app.Add (cbSupportsTrueColor);
+
+        var cbUseTrueColor = new CheckBox
+        {
+            X = Pos.Right (cbSupportsTrueColor) + 1,
+            Y = Pos.Top (lblDriverName),
+            CheckedState = Application.Force16Colors ? CheckState.Checked : CheckState.UnChecked,
+            Enabled = canTrueColor,
+            Text = "Force16Colors"
+        };
+        cbUseTrueColor.CheckedStateChanging += (_, evt) => { Application.Force16Colors = evt.Result == CheckState.Checked; };
+        app.Add (lblDriverName, cbSupportsTrueColor, cbUseTrueColor);
         // Set default colors.
         // Set default colors.
         foregroundColorPicker.SelectedColor = _demoView.SuperView!.GetAttributeForRole (VisualRole.Normal).Foreground.GetClosestNamedColor16 ();
         foregroundColorPicker.SelectedColor = _demoView.SuperView!.GetAttributeForRole (VisualRole.Normal).Foreground.GetClosestNamedColor16 ();
         backgroundColorPicker.SelectedColor = _demoView.SuperView.GetAttributeForRole (VisualRole.Normal).Background.GetClosestNamedColor16 ();
         backgroundColorPicker.SelectedColor = _demoView.SuperView.GetAttributeForRole (VisualRole.Normal).Background.GetClosestNamedColor16 ();

+ 15 - 4
Examples/UICatalog/Scenarios/CombiningMarks.cs

@@ -8,15 +8,16 @@ public class CombiningMarks : Scenario
     public override void Main ()
     public override void Main ()
     {
     {
         Application.Init ();
         Application.Init ();
-        var top = new Toplevel ();
+        var top = new Runnable ();
 
 
         top.DrawComplete += (s, e) =>
         top.DrawComplete += (s, e) =>
         {
         {
             // Forces reset _lineColsOffset because we're dealing with direct draw
             // Forces reset _lineColsOffset because we're dealing with direct draw
-            Application.Current!.SetNeedsDraw ();
+            Application.TopRunnableView!.SetNeedsDraw ();
 
 
             var i = -1;
             var i = -1;
-            top.AddStr ("Terminal.Gui only supports combining marks that normalize. See Issue #2616.");
+            top.Move (0, ++i);
+            top.AddStr ("Terminal.Gui supports all combining sequences that can be rendered as an unique grapheme.");
             top.Move (0, ++i);
             top.Move (0, ++i);
             top.AddStr ("\u0301<- \"\\u0301\" using AddStr.");
             top.AddStr ("\u0301<- \"\\u0301\" using AddStr.");
             top.Move (0, ++i);
             top.Move (0, ++i);
@@ -38,7 +39,7 @@ public class CombiningMarks : Scenario
             top.AddRune ('\u0301');
             top.AddRune ('\u0301');
             top.AddRune ('\u0328');
             top.AddRune ('\u0328');
             top.AddRune (']');
             top.AddRune (']');
-            top.AddStr ("<- \"[a\\u0301\\u0301\\u0328]\" using AddRune for each.");
+            top.AddStr ("<- \"[a\\u0301\\u0301\\u0328]\" using AddRune for each. Avoid use AddRune for combining sequences because may result with empty blocks at end.");
             top.Move (0, ++i);
             top.Move (0, ++i);
             top.AddStr ("[a\u0301\u0301\u0328]<- \"[a\\u0301\\u0301\\u0328]\" using AddStr.");
             top.AddStr ("[a\u0301\u0301\u0328]<- \"[a\\u0301\\u0301\\u0328]\" using AddStr.");
             top.Move (0, ++i);
             top.Move (0, ++i);
@@ -82,6 +83,16 @@ public class CombiningMarks : Scenario
             top.AddStr ("[\U0001F468\U0001F469\U0001F9D2]<- \"[\\U0001F468\\U0001F469\\U0001F9D2]\" using AddStr.");
             top.AddStr ("[\U0001F468\U0001F469\U0001F9D2]<- \"[\\U0001F468\\U0001F469\\U0001F9D2]\" using AddStr.");
             top.Move (0, ++i);
             top.Move (0, ++i);
             top.AddStr ("[\U0001F468\u200D\U0001F469\u200D\U0001F9D2]<- \"[\\U0001F468\\u200D\\U0001F469\\u200D\\U0001F9D2]\" using AddStr.");
             top.AddStr ("[\U0001F468\u200D\U0001F469\u200D\U0001F9D2]<- \"[\\U0001F468\\u200D\\U0001F469\\u200D\\U0001F9D2]\" using AddStr.");
+            top.Move (0, ++i);
+            top.AddStr ("[\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466]<- \"[\\U0001F468\\u200D\\U0001F469\\u200D\\U0001F467\\u200D\\U0001F466]\" using AddStr.");
+            top.Move (0, ++i);
+            top.AddStr ("[\u0e32\u0e33]<- \"[\\u0e32\\u0e33]\" using AddStr.");
+            top.Move (0, ++i);
+            top.AddStr ("[\U0001F469\u200D\u2764\uFE0F\u200D\U0001F48B\u200D\U0001F468]<- \"[\\U0001F469\\u200D\\u2764\\uFE0F\\u200D\\U0001F48B\\u200D\\U0001F468]\" using AddStr.");
+            top.Move (0, ++i);
+            top.AddStr ("[\u0061\uFE20\u0065\uFE21]<- \"[\\u0061\\uFE20\\u0065\\uFE21]\" using AddStr.");
+            top.Move (0, ++i);
+            top.AddStr ("[\u1100\uD7B0]<- \"[\\u1100\\uD7B0]\" using AddStr.");
         };
         };
 
 
         Application.Run (top);
         Application.Run (top);

+ 1 - 1
Examples/UICatalog/Scenarios/ComboBoxIteration.cs

@@ -25,7 +25,7 @@ public class ComboBoxIteration : Scenario
 
 
         var lbComboBox = new Label
         var lbComboBox = new Label
         {
         {
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             X = Pos.Right (lbListView) + 1,
             X = Pos.Right (lbListView) + 1,
             Width = Dim.Percent (40)
             Width = Dim.Percent (40)
         };
         };

+ 1 - 1
Examples/UICatalog/Scenarios/ComputedLayout.cs

@@ -280,7 +280,7 @@ public class ComputedLayout : Scenario
             Y = Pos.Percent (50),
             Y = Pos.Percent (50),
             Width = Dim.Percent (80),
             Width = Dim.Percent (80),
             Height = Dim.Percent (10),
             Height = Dim.Percent (10),
-            SchemeName = "TopLevel"
+            SchemeName = "Runnable"
         };
         };
 
 
         textView.Text =
         textView.Text =

+ 5 - 5
Examples/UICatalog/Scenarios/ConfigurationEditor.cs

@@ -60,7 +60,7 @@ public class ConfigurationEditor : Scenario
 
 
         win.Add (_tabView, statusBar);
         win.Add (_tabView, statusBar);
 
 
-        win.Loaded += (s, a) =>
+        win.IsModalChanged += (s, a) =>
                       {
                       {
                           Open ();
                           Open ();
                       };
                       };
@@ -75,7 +75,7 @@ public class ConfigurationEditor : Scenario
 
 
         void ConfigurationManagerOnApplied (object? sender, ConfigurationManagerEventArgs e)
         void ConfigurationManagerOnApplied (object? sender, ConfigurationManagerEventArgs e)
         {
         {
-            Application.Current?.SetNeedsDraw ();
+            Application.TopRunnableView?.SetNeedsDraw ();
         }
         }
     }
     }
     public void Save ()
     public void Save ()
@@ -153,9 +153,9 @@ public class ConfigurationEditor : Scenario
                 continue;
                 continue;
             }
             }
 
 
-            int result = MessageBox.Query (
+            int? result = MessageBox.Query (editor?.App,
                                            "Save Changes",
                                            "Save Changes",
-                                           $"Save changes to {editor.FileInfo!.Name}",
+                                           $"Save changes to {editor?.FileInfo!.Name}",
                                            "_Yes",
                                            "_Yes",
                                            "_No",
                                            "_No",
                                            "_Cancel"
                                            "_Cancel"
@@ -164,7 +164,7 @@ public class ConfigurationEditor : Scenario
             switch (result)
             switch (result)
             {
             {
                 case 0:
                 case 0:
-                    editor.Save ();
+                    editor?.Save ();
 
 
                     break;
                     break;
 
 

+ 23 - 19
Examples/UICatalog/Scenarios/ContextMenus.cs

@@ -26,7 +26,7 @@ public class ContextMenus : Scenario
         {
         {
             Title = GetQuitKeyAndName (),
             Title = GetQuitKeyAndName (),
             Arrangement = ViewArrangement.Fixed,
             Arrangement = ViewArrangement.Fixed,
-            SchemeName = "Toplevel"
+            SchemeName = "Runnable"
         };
         };
 
 
         _appWindow.Initialized += AppWindowOnInitialized;
         _appWindow.Initialized += AppWindowOnInitialized;
@@ -49,7 +49,7 @@ public class ContextMenus : Scenario
             var text = "Context Menu";
             var text = "Context Menu";
             var width = 20;
             var width = 20;
 
 
-            CreateWinContextMenu ();
+            CreateWinContextMenu (ApplicationImpl.Instance);
 
 
             var label = new Label
             var label = new Label
             {
             {
@@ -84,7 +84,11 @@ public class ContextMenus : Scenario
             _appWindow.MouseClick += OnAppWindowOnMouseClick;
             _appWindow.MouseClick += OnAppWindowOnMouseClick;
 
 
             CultureInfo originalCulture = Thread.CurrentThread.CurrentUICulture;
             CultureInfo originalCulture = Thread.CurrentThread.CurrentUICulture;
-            _appWindow.Closed += (s, e) => { Thread.CurrentThread.CurrentUICulture = originalCulture; };
+            _appWindow.IsRunningChanged += (s, e) => {
+                                               if (!e.Value)
+                                               {
+                                                   Thread.CurrentThread.CurrentUICulture = originalCulture;
+                                               } };
         }
         }
 
 
         void OnAppWindowOnMouseClick (object? s, MouseEventArgs e)
         void OnAppWindowOnMouseClick (object? s, MouseEventArgs e)
@@ -108,21 +112,21 @@ public class ContextMenus : Scenario
         }
         }
     }
     }
 
 
-    private void CreateWinContextMenu ()
+    private void CreateWinContextMenu (IApplication? app)
     {
     {
         _winContextMenu = new (
         _winContextMenu = new (
                                [
                                [
-                                   new MenuItemv2
+                                   new MenuItem
                                    {
                                    {
                                        Title = "C_ultures",
                                        Title = "C_ultures",
                                        SubMenu = GetSupportedCultureMenu (),
                                        SubMenu = GetSupportedCultureMenu (),
                                    },
                                    },
                                    new Line (),
                                    new Line (),
-                                   new MenuItemv2
+                                   new MenuItem
                                    {
                                    {
                                        Title = "_Configuration...",
                                        Title = "_Configuration...",
                                        HelpText = "Show configuration",
                                        HelpText = "Show configuration",
-                                       Action = () => MessageBox.Query (
+                                       Action = () => MessageBox.Query (app,
                                                                         50,
                                                                         50,
                                                                         10,
                                                                         10,
                                                                         "Configuration",
                                                                         "Configuration",
@@ -130,17 +134,17 @@ public class ContextMenus : Scenario
                                                                         "Ok"
                                                                         "Ok"
                                                                        )
                                                                        )
                                    },
                                    },
-                                   new MenuItemv2
+                                   new MenuItem
                                    {
                                    {
                                        Title = "M_ore options",
                                        Title = "M_ore options",
                                        SubMenu = new (
                                        SubMenu = new (
                                                       [
                                                       [
-                                                          new MenuItemv2
+                                                          new MenuItem
                                                           {
                                                           {
                                                               Title = "_Setup...",
                                                               Title = "_Setup...",
                                                               HelpText = "Perform setup",
                                                               HelpText = "Perform setup",
                                                               Action = () => MessageBox
                                                               Action = () => MessageBox
-                                                                           .Query (
+                                                                           .Query (app,
                                                                                    50,
                                                                                    50,
                                                                                    10,
                                                                                    10,
                                                                                    "Setup",
                                                                                    "Setup",
@@ -149,12 +153,12 @@ public class ContextMenus : Scenario
                                                                                   ),
                                                                                   ),
                                                               Key = Key.T.WithCtrl
                                                               Key = Key.T.WithCtrl
                                                           },
                                                           },
-                                                          new MenuItemv2
+                                                          new MenuItem
                                                           {
                                                           {
                                                               Title = "_Maintenance...",
                                                               Title = "_Maintenance...",
                                                               HelpText = "Maintenance mode",
                                                               HelpText = "Maintenance mode",
                                                               Action = () => MessageBox
                                                               Action = () => MessageBox
-                                                                           .Query (
+                                                                           .Query (app,
                                                                                    50,
                                                                                    50,
                                                                                    10,
                                                                                    10,
                                                                                    "Maintenance",
                                                                                    "Maintenance",
@@ -165,7 +169,7 @@ public class ContextMenus : Scenario
                                                       ])
                                                       ])
                                    },
                                    },
                                    new Line (),
                                    new Line (),
-                                   new MenuItemv2
+                                   new MenuItem
                                    {
                                    {
                                        Title = "_Quit",
                                        Title = "_Quit",
                                        Action = () => Application.RequestStop ()
                                        Action = () => Application.RequestStop ()
@@ -177,14 +181,14 @@ public class ContextMenus : Scenario
         Application.Popover?.Register (_winContextMenu);
         Application.Popover?.Register (_winContextMenu);
     }
     }
 
 
-    private Menuv2 GetSupportedCultureMenu ()
+    private Menu GetSupportedCultureMenu ()
     {
     {
-        List<MenuItemv2> supportedCultures = [];
+        List<MenuItem> supportedCultures = [];
         int index = -1;
         int index = -1;
 
 
         foreach (CultureInfo c in _cultureInfos!)
         foreach (CultureInfo c in _cultureInfos!)
         {
         {
-            MenuItemv2 culture = new ();
+            MenuItem culture = new ();
 
 
             culture.CommandView = new CheckBox { CanFocus = false };
             culture.CommandView = new CheckBox { CanFocus = false };
 
 
@@ -215,17 +219,17 @@ public class ContextMenus : Scenario
             supportedCultures.Add (culture);
             supportedCultures.Add (culture);
         }
         }
 
 
-        Menuv2 menu = new (supportedCultures.ToArray ());
+        Menu menu = new (supportedCultures.ToArray ());
 
 
         return menu;
         return menu;
 
 
-        void CreateAction (List<MenuItemv2> cultures, MenuItemv2 culture)
+        void CreateAction (List<MenuItem> cultures, MenuItem culture)
         {
         {
             culture.Action += () =>
             culture.Action += () =>
                               {
                               {
                                   Thread.CurrentThread.CurrentUICulture = new (culture.HelpText);
                                   Thread.CurrentThread.CurrentUICulture = new (culture.HelpText);
 
 
-                                  foreach (MenuItemv2 item in cultures)
+                                  foreach (MenuItem item in cultures)
                                   {
                                   {
                                       ((CheckBox)item.CommandView).CheckedState =
                                       ((CheckBox)item.CommandView).CheckedState =
                                           Thread.CurrentThread.CurrentUICulture.Name == item.HelpText ? CheckState.Checked : CheckState.UnChecked;
                                           Thread.CurrentThread.CurrentUICulture.Name == item.HelpText ? CheckState.Checked : CheckState.UnChecked;

+ 270 - 211
Examples/UICatalog/Scenarios/CsvEditor.cs

@@ -1,8 +1,7 @@
-using System;
+#nullable enable
+
 using System.Data;
 using System.Data;
 using System.Globalization;
 using System.Globalization;
-using System.IO;
-using System.Linq;
 using System.Text.RegularExpressions;
 using System.Text.RegularExpressions;
 using CsvHelper;
 using CsvHelper;
 
 
@@ -14,99 +13,37 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("Controls")]
 [ScenarioCategory ("Controls")]
 [ScenarioCategory ("Dialogs")]
 [ScenarioCategory ("Dialogs")]
 [ScenarioCategory ("Text and Formatting")]
 [ScenarioCategory ("Text and Formatting")]
-[ScenarioCategory ("Dialogs")]
 [ScenarioCategory ("Arrangement")]
 [ScenarioCategory ("Arrangement")]
 [ScenarioCategory ("Files and IO")]
 [ScenarioCategory ("Files and IO")]
 public class CsvEditor : Scenario
 public class CsvEditor : Scenario
 {
 {
-    private string _currentFile;
-    private DataTable _currentTable;
-    private MenuItem _miCentered;
-    private MenuItem _miLeft;
-    private MenuItem _miRight;
-    private TextField _selectedCellTextField;
-    private TableView _tableView;
+    private string? _currentFile;
+    private DataTable? _currentTable;
+    private CheckBox? _miCenteredCheckBox;
+    private CheckBox? _miLeftCheckBox;
+    private CheckBox? _miRightCheckBox;
+    private TextField? _selectedCellTextField;
+    private TableView? _tableView;
 
 
     public override void Main ()
     public override void Main ()
     {
     {
-        // Init
         Application.Init ();
         Application.Init ();
 
 
-        // Setup - Create a top-level application window and configure it.
-        Toplevel appWindow = new ()
+        Window appWindow = new ()
         {
         {
-            Title = $"{GetName ()}"
+            Title = GetName ()
         };
         };
 
 
-        //appWindow.Height = Dim.Fill (1); // status bar
-
-        _tableView = new () { X = 0, Y = 1, Width = Dim.Fill (), Height = Dim.Fill (2) };
+        // MenuBar
+        MenuBar menu = new ();
 
 
-        var fileMenu = new MenuBarItem (
-                                        "_File",
-                                        new MenuItem []
-                                        {
-                                            new ("_Open CSV", "", () => Open ()),
-                                            new ("_Save", "", () => Save ()),
-                                            new ("_Quit", "Quits The App", () => Quit ())
-                                        }
-                                       );
-
-        //fileMenu.Help = "Help";
-        var menu = new MenuBar
-        {
-            Menus =
-            [
-                fileMenu,
-                new (
-                     "_Edit",
-                     new MenuItem []
-                     {
-                         new ("_New Column", "", () => AddColumn ()),
-                         new ("_New Row", "", () => AddRow ()),
-                         new (
-                              "_Rename Column",
-                              "",
-                              () => RenameColumn ()
-                             ),
-                         new ("_Delete Column", "", () => DeleteColum ()),
-                         new ("_Move Column", "", () => MoveColumn ()),
-                         new ("_Move Row", "", () => MoveRow ()),
-                         new ("_Sort Asc", "", () => Sort (true)),
-                         new ("_Sort Desc", "", () => Sort (false))
-                     }
-                    ),
-                new (
-                     "_View",
-                     new []
-                     {
-                         _miLeft = new (
-                                        "_Align Left",
-                                        "",
-                                        () => Align (Alignment.Start)
-                                       ),
-                         _miRight = new (
-                                         "_Align Right",
-                                         "",
-                                         () => Align (Alignment.End)
-                                        ),
-                         _miCentered = new (
-                                            "_Align Centered",
-                                            "",
-                                            () => Align (Alignment.Center)
-                                           ),
-
-                         // Format requires hard typed data table, when we read a CSV everything is untyped (string) so this only works for new columns in this demo
-                         _miCentered = new (
-                                            "_Set Format Pattern",
-                                            "",
-                                            () => SetFormat ()
-                                           )
-                     }
-                    )
-            ]
+        _tableView = new ()
+        {
+            X = 0,
+            Y = Pos.Bottom (menu),
+            Width = Dim.Fill (),
+            Height = Dim.Fill (1)
         };
         };
-        appWindow.Add (menu);
 
 
         _selectedCellTextField = new ()
         _selectedCellTextField = new ()
         {
         {
@@ -116,57 +53,169 @@ public class CsvEditor : Scenario
         };
         };
         _selectedCellTextField.TextChanged += SelectedCellLabel_TextChanged;
         _selectedCellTextField.TextChanged += SelectedCellLabel_TextChanged;
 
 
-        var statusBar = new StatusBar (
-                                       [
-                                           new (Application.QuitKey, "Quit", Quit, "Quit!"),
-                                           new (Key.O.WithCtrl, "Open", Open, "Open a file."),
-                                           new (Key.S.WithCtrl, "Save", Save, "Save current."),
-                                           new ()
-                                           {
-                                               HelpText = "Cell:",
-                                               CommandView = _selectedCellTextField,
-                                               AlignmentModes = AlignmentModes.StartToEnd | AlignmentModes.IgnoreFirstOrLast,
-                                               Enabled = false
-                                           }
-                                       ])
+        // StatusBar
+        StatusBar statusBar = new (
+                                   [
+                                       new (Application.QuitKey, "Quit", Quit, "Quit!"),
+                                       new (Key.O.WithCtrl, "Open", Open, "Open a file."),
+                                       new (Key.S.WithCtrl, "Save", Save, "Save current."),
+                                       new ()
+                                       {
+                                           HelpText = "Cell:",
+                                           CommandView = _selectedCellTextField,
+                                           AlignmentModes = AlignmentModes.StartToEnd | AlignmentModes.IgnoreFirstOrLast,
+                                           Enabled = false
+                                       }
+                                   ]
+                                  )
         {
         {
             AlignmentModes = AlignmentModes.IgnoreFirstOrLast
             AlignmentModes = AlignmentModes.IgnoreFirstOrLast
         };
         };
-        appWindow.Add (statusBar);
 
 
-        appWindow.Add (_tableView);
+        // Setup menu checkboxes for alignment
+        _miLeftCheckBox = new ()
+        {
+            Title = "_Align Left"
+        };
+        _miLeftCheckBox.CheckedStateChanged += (s, e) => Align (Alignment.Start);
+
+        _miRightCheckBox = new ()
+        {
+            Title = "_Align Right"
+        };
+        _miRightCheckBox.CheckedStateChanged += (s, e) => Align (Alignment.End);
+
+        _miCenteredCheckBox = new ()
+        {
+            Title = "_Align Centered"
+        };
+        _miCenteredCheckBox.CheckedStateChanged += (s, e) => Align (Alignment.Center);
+
+        MenuBarItem fileMenu = new (
+                                    "_File",
+                                    [
+                                        new MenuItem
+                                        {
+                                            Title = "_Open CSV",
+                                            Action = Open
+                                        },
+                                        new MenuItem
+                                        {
+                                            Title = "_Save",
+                                            Action = Save
+                                        },
+                                        new MenuItem
+                                        {
+                                            Title = "_Quit",
+                                            HelpText = "Quits The App",
+                                            Action = Quit
+                                        }
+                                    ]
+                                   );
+
+        menu.Add (fileMenu);
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_Edit",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_New Column",
+                                           Action = AddColumn
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_New Row",
+                                           Action = AddRow
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Rename Column",
+                                           Action = RenameColumn
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Delete Column",
+                                           Action = DeleteColum
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Move Column",
+                                           Action = MoveColumn
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Move Row",
+                                           Action = MoveRow
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Sort Asc",
+                                           Action = () => Sort (true)
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Sort Desc",
+                                           Action = () => Sort (false)
+                                       }
+                                   ]
+                                  )
+                 );
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_View",
+                                   [
+                                       new MenuItem
+                                       {
+                                           CommandView = _miLeftCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miRightCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miCenteredCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Set Format Pattern",
+                                           Action = SetFormat
+                                       }
+                                   ]
+                                  )
+                 );
+
+        appWindow.Add (menu, _tableView, statusBar);
 
 
         _tableView.SelectedCellChanged += OnSelectedCellChanged;
         _tableView.SelectedCellChanged += OnSelectedCellChanged;
         _tableView.CellActivated += EditCurrentCell;
         _tableView.CellActivated += EditCurrentCell;
         _tableView.KeyDown += TableViewKeyPress;
         _tableView.KeyDown += TableViewKeyPress;
 
 
-        //SetupScrollBar ();
-
-        // Run - Start the application.
         Application.Run (appWindow);
         Application.Run (appWindow);
         appWindow.Dispose ();
         appWindow.Dispose ();
-
-        // Shutdown - Calling Application.Shutdown is required.
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
     private void AddColumn ()
     private void AddColumn ()
     {
     {
-        if (NoTableLoaded ())
+        if (NoTableLoaded () || _tableView is null || _currentTable is null)
         {
         {
             return;
             return;
         }
         }
 
 
         if (GetText ("Enter column name", "Name:", "", out string colName))
         if (GetText ("Enter column name", "Name:", "", out string colName))
         {
         {
-            var col = new DataColumn (colName);
+            DataColumn col = new (colName);
 
 
             int newColIdx = Math.Min (
             int newColIdx = Math.Min (
                                       Math.Max (0, _tableView.SelectedColumn + 1),
                                       Math.Max (0, _tableView.SelectedColumn + 1),
                                       _tableView.Table.Columns
                                       _tableView.Table.Columns
                                      );
                                      );
 
 
-            int result = MessageBox.Query (
+            int? result = MessageBox.Query (ApplicationImpl.Instance,
                                            "Column Type",
                                            "Column Type",
                                            "Pick a data type for the column",
                                            "Pick a data type for the column",
                                            "Date",
                                            "Date",
@@ -176,7 +225,7 @@ public class CsvEditor : Scenario
                                            "Cancel"
                                            "Cancel"
                                           );
                                           );
 
 
-            if (result <= -1 || result >= 4)
+            if (result is null || result >= 4)
             {
             {
                 return;
                 return;
             }
             }
@@ -209,7 +258,7 @@ public class CsvEditor : Scenario
 
 
     private void AddRow ()
     private void AddRow ()
     {
     {
-        if (NoTableLoaded ())
+        if (NoTableLoaded () || _currentTable is null || _tableView is null)
         {
         {
             return;
             return;
         }
         }
@@ -224,7 +273,7 @@ public class CsvEditor : Scenario
 
 
     private void Align (Alignment newAlignment)
     private void Align (Alignment newAlignment)
     {
     {
-        if (NoTableLoaded ())
+        if (NoTableLoaded () || _tableView is null)
         {
         {
             return;
             return;
         }
         }
@@ -232,31 +281,34 @@ public class CsvEditor : Scenario
         ColumnStyle style = _tableView.Style.GetOrCreateColumnStyle (_tableView.SelectedColumn);
         ColumnStyle style = _tableView.Style.GetOrCreateColumnStyle (_tableView.SelectedColumn);
         style.Alignment = newAlignment;
         style.Alignment = newAlignment;
 
 
-        _miLeft.Checked = style.Alignment == Alignment.Start;
-        _miRight.Checked = style.Alignment == Alignment.End;
-        _miCentered.Checked = style.Alignment == Alignment.Center;
+        if (_miLeftCheckBox is { })
+        {
+            _miLeftCheckBox.CheckedState = style.Alignment == Alignment.Start ? CheckState.Checked : CheckState.UnChecked;
+        }
 
 
-        _tableView.Update ();
-    }
+        if (_miRightCheckBox is { })
+        {
+            _miRightCheckBox.CheckedState = style.Alignment == Alignment.End ? CheckState.Checked : CheckState.UnChecked;
+        }
+
+        if (_miCenteredCheckBox is { })
+        {
+            _miCenteredCheckBox.CheckedState = style.Alignment == Alignment.Center ? CheckState.Checked : CheckState.UnChecked;
+        }
 
 
-    private void ClearColumnStyles ()
-    {
-        _tableView.Style.ColumnStyles.Clear ();
         _tableView.Update ();
         _tableView.Update ();
     }
     }
 
 
-    private void CloseExample () { _tableView.Table = null; }
-
     private void DeleteColum ()
     private void DeleteColum ()
     {
     {
-        if (NoTableLoaded ())
+        if (NoTableLoaded () || _tableView is null || _currentTable is null)
         {
         {
             return;
             return;
         }
         }
 
 
         if (_tableView.SelectedColumn == -1)
         if (_tableView.SelectedColumn == -1)
         {
         {
-            MessageBox.ErrorQuery ("No Column", "No column selected", "Ok");
+            MessageBox.ErrorQuery (ApplicationImpl.Instance, "No Column", "No column selected", "Ok");
 
 
             return;
             return;
         }
         }
@@ -268,20 +320,20 @@ public class CsvEditor : Scenario
         }
         }
         catch (Exception ex)
         catch (Exception ex)
         {
         {
-            MessageBox.ErrorQuery ("Could not remove column", ex.Message, "Ok");
+            MessageBox.ErrorQuery (ApplicationImpl.Instance, "Could not remove column", ex.Message, "Ok");
         }
         }
     }
     }
 
 
-    private void EditCurrentCell (object sender, CellActivatedEventArgs e)
+    private void EditCurrentCell (object? sender, CellActivatedEventArgs e)
     {
     {
-        if (e.Table == null)
+        if (e.Table is null || _currentTable is null || _tableView is null)
         {
         {
             return;
             return;
         }
         }
 
 
         var oldValue = _currentTable.Rows [e.Row] [e.Col].ToString ();
         var oldValue = _currentTable.Rows [e.Row] [e.Col].ToString ();
 
 
-        if (GetText ("Enter new value", _currentTable.Columns [e.Col].ColumnName, oldValue, out string newText))
+        if (GetText ("Enter new value", _currentTable.Columns [e.Col].ColumnName, oldValue ?? "", out string newText))
         {
         {
             try
             try
             {
             {
@@ -290,7 +342,7 @@ public class CsvEditor : Scenario
             }
             }
             catch (Exception ex)
             catch (Exception ex)
             {
             {
-                MessageBox.ErrorQuery (60, 20, "Failed to set text", ex.Message, "Ok");
+                MessageBox.ErrorQuery (ApplicationImpl.Instance, 60, 20, "Failed to set text", ex.Message, "Ok");
             }
             }
 
 
             _tableView.Update ();
             _tableView.Update ();
@@ -301,20 +353,20 @@ public class CsvEditor : Scenario
     {
     {
         var okPressed = false;
         var okPressed = false;
 
 
-        var ok = new Button { Text = "Ok", IsDefault = true };
+        Button ok = new () { Text = "Ok", IsDefault = true };
 
 
         ok.Accepting += (s, e) =>
         ok.Accepting += (s, e) =>
-                     {
-                         okPressed = true;
-                         Application.RequestStop ();
-                     };
-        var cancel = new Button { Text = "Cancel" };
+                        {
+                            okPressed = true;
+                            Application.RequestStop ();
+                        };
+        Button cancel = new () { Text = "Cancel" };
         cancel.Accepting += (s, e) => { Application.RequestStop (); };
         cancel.Accepting += (s, e) => { Application.RequestStop (); };
-        var d = new Dialog { Title = title, Buttons = [ok, cancel] };
+        Dialog d = new () { Title = title, Buttons = [ok, cancel] };
 
 
-        var lbl = new Label { X = 0, Y = 1, Text = label };
+        Label lbl = new () { X = 0, Y = 1, Text = label };
 
 
-        var tf = new TextField { Text = initialText, X = 0, Y = 2, Width = Dim.Fill () };
+        TextField tf = new () { Text = initialText, X = 0, Y = 2, Width = Dim.Fill () };
 
 
         d.Add (lbl, tf);
         d.Add (lbl, tf);
         tf.SetFocus ();
         tf.SetFocus ();
@@ -322,21 +374,21 @@ public class CsvEditor : Scenario
         Application.Run (d);
         Application.Run (d);
         d.Dispose ();
         d.Dispose ();
 
 
-        enteredText = okPressed ? tf.Text : null;
+        enteredText = okPressed ? tf.Text : string.Empty;
 
 
         return okPressed;
         return okPressed;
     }
     }
 
 
     private void MoveColumn ()
     private void MoveColumn ()
     {
     {
-        if (NoTableLoaded ())
+        if (NoTableLoaded () || _currentTable is null || _tableView is null)
         {
         {
             return;
             return;
         }
         }
 
 
         if (_tableView.SelectedColumn == -1)
         if (_tableView.SelectedColumn == -1)
         {
         {
-            MessageBox.ErrorQuery ("No Column", "No column selected", "Ok");
+            MessageBox.ErrorQuery (ApplicationImpl.Instance, "No Column", "No column selected", "Ok");
 
 
             return;
             return;
         }
         }
@@ -361,20 +413,20 @@ public class CsvEditor : Scenario
         }
         }
         catch (Exception ex)
         catch (Exception ex)
         {
         {
-            MessageBox.ErrorQuery ("Error moving column", ex.Message, "Ok");
+            MessageBox.ErrorQuery (ApplicationImpl.Instance, "Error moving column", ex.Message, "Ok");
         }
         }
     }
     }
 
 
     private void MoveRow ()
     private void MoveRow ()
     {
     {
-        if (NoTableLoaded ())
+        if (NoTableLoaded () || _currentTable is null || _tableView is null)
         {
         {
             return;
             return;
         }
         }
 
 
         if (_tableView.SelectedRow == -1)
         if (_tableView.SelectedRow == -1)
         {
         {
-            MessageBox.ErrorQuery ("No Rows", "No row selected", "Ok");
+            MessageBox.ErrorQuery (ApplicationImpl.Instance, "No Rows", "No row selected", "Ok");
 
 
             return;
             return;
         }
         }
@@ -394,7 +446,7 @@ public class CsvEditor : Scenario
                     return;
                     return;
                 }
                 }
 
 
-                object [] arrayItems = currentRow.ItemArray;
+                object? [] arrayItems = currentRow.ItemArray;
                 _currentTable.Rows.Remove (currentRow);
                 _currentTable.Rows.Remove (currentRow);
 
 
                 // Removing and Inserting the same DataRow seems to result in it loosing its values so we have to create a new instance
                 // Removing and Inserting the same DataRow seems to result in it loosing its values so we have to create a new instance
@@ -410,15 +462,15 @@ public class CsvEditor : Scenario
         }
         }
         catch (Exception ex)
         catch (Exception ex)
         {
         {
-            MessageBox.ErrorQuery ("Error moving column", ex.Message, "Ok");
+            MessageBox.ErrorQuery (ApplicationImpl.Instance, "Error moving column", ex.Message, "Ok");
         }
         }
     }
     }
 
 
     private bool NoTableLoaded ()
     private bool NoTableLoaded ()
     {
     {
-        if (_tableView.Table == null)
+        if (_tableView?.Table is null)
         {
         {
-            MessageBox.ErrorQuery ("No Table Loaded", "No table has currently be opened", "Ok");
+            MessageBox.ErrorQuery (ApplicationImpl.Instance, "No Table Loaded", "No table has currently be opened", "Ok");
 
 
             return true;
             return true;
         }
         }
@@ -426,31 +478,47 @@ public class CsvEditor : Scenario
         return false;
         return false;
     }
     }
 
 
-    private void OnSelectedCellChanged (object sender, SelectedCellChangedEventArgs e)
+    private void OnSelectedCellChanged (object? sender, SelectedCellChangedEventArgs e)
     {
     {
+        if (_selectedCellTextField is null || _tableView is null)
+        {
+            return;
+        }
+
         // only update the text box if the user is not manually editing it
         // only update the text box if the user is not manually editing it
         if (!_selectedCellTextField.HasFocus)
         if (!_selectedCellTextField.HasFocus)
         {
         {
             _selectedCellTextField.Text = $"{_tableView.SelectedRow},{_tableView.SelectedColumn}";
             _selectedCellTextField.Text = $"{_tableView.SelectedRow},{_tableView.SelectedColumn}";
         }
         }
 
 
-        if (_tableView.Table == null || _tableView.SelectedColumn == -1)
+        if (_tableView.Table is null || _tableView.SelectedColumn == -1)
         {
         {
             return;
             return;
         }
         }
 
 
-        ColumnStyle style = _tableView.Style.GetColumnStyleIfAny (_tableView.SelectedColumn);
+        ColumnStyle? style = _tableView.Style.GetColumnStyleIfAny (_tableView.SelectedColumn);
+
+        if (_miLeftCheckBox is { })
+        {
+            _miLeftCheckBox.CheckedState = style?.Alignment == Alignment.Start ? CheckState.Checked : CheckState.UnChecked;
+        }
+
+        if (_miRightCheckBox is { })
+        {
+            _miRightCheckBox.CheckedState = style?.Alignment == Alignment.End ? CheckState.Checked : CheckState.UnChecked;
+        }
 
 
-        _miLeft.Checked = style?.Alignment == Alignment.Start;
-        _miRight.Checked = style?.Alignment == Alignment.End;
-        _miCentered.Checked = style?.Alignment == Alignment.Center;
+        if (_miCenteredCheckBox is { })
+        {
+            _miCenteredCheckBox.CheckedState = style?.Alignment == Alignment.Center ? CheckState.Checked : CheckState.UnChecked;
+        }
     }
     }
 
 
     private void Open ()
     private void Open ()
     {
     {
-        var ofd = new FileDialog
+        FileDialog ofd = new ()
         {
         {
-            AllowedTypes = new () { new AllowedType ("Comma Separated Values", ".csv") }
+            AllowedTypes = [new AllowedType ("Comma Separated Values", ".csv")]
         };
         };
         ofd.Style.OkButtonText = "Open";
         ofd.Style.OkButtonText = "Open";
 
 
@@ -471,13 +539,13 @@ public class CsvEditor : Scenario
 
 
         try
         try
         {
         {
-            using var reader = new CsvReader (File.OpenText (filename), CultureInfo.InvariantCulture);
+            using CsvReader reader = new (File.OpenText (filename), CultureInfo.InvariantCulture);
 
 
-            var dt = new DataTable ();
+            DataTable dt = new ();
 
 
             reader.Read ();
             reader.Read ();
 
 
-            if (reader.ReadHeader ())
+            if (reader.ReadHeader () && reader.HeaderRecord is { })
             {
             {
                 foreach (string h in reader.HeaderRecord)
                 foreach (string h in reader.HeaderRecord)
                 {
                 {
@@ -501,12 +569,20 @@ public class CsvEditor : Scenario
 
 
             // Only set the current filename if we successfully loaded the entire file
             // Only set the current filename if we successfully loaded the entire file
             _currentFile = filename;
             _currentFile = filename;
-            _selectedCellTextField.SuperView.Enabled = true;
-            Application.Current.Title = $"{GetName ()} - {Path.GetFileName (_currentFile)}";
+
+            if (_selectedCellTextField?.SuperView is { })
+            {
+                _selectedCellTextField.SuperView.Enabled = true;
+            }
+
+            if (Application.TopRunnableView is { })
+            {
+                Application.TopRunnableView.Title = $"{GetName ()} - {Path.GetFileName (_currentFile)}";
+            }
         }
         }
         catch (Exception ex)
         catch (Exception ex)
         {
         {
-            MessageBox.ErrorQuery (
+            MessageBox.ErrorQuery (ApplicationImpl.Instance,
                                    "Open Failed",
                                    "Open Failed",
                                    $"Error on line {lineNumber}{Environment.NewLine}{ex.Message}",
                                    $"Error on line {lineNumber}{Environment.NewLine}{ex.Message}",
                                    "Ok"
                                    "Ok"
@@ -518,7 +594,7 @@ public class CsvEditor : Scenario
 
 
     private void RenameColumn ()
     private void RenameColumn ()
     {
     {
-        if (NoTableLoaded ())
+        if (NoTableLoaded () || _currentTable is null || _tableView is null)
         {
         {
             return;
             return;
         }
         }
@@ -534,17 +610,17 @@ public class CsvEditor : Scenario
 
 
     private void Save ()
     private void Save ()
     {
     {
-        if (_tableView.Table == null || string.IsNullOrWhiteSpace (_currentFile))
+        if (_tableView?.Table is null || string.IsNullOrWhiteSpace (_currentFile) || _currentTable is null)
         {
         {
-            MessageBox.ErrorQuery ("No file loaded", "No file is currently loaded", "Ok");
+            MessageBox.ErrorQuery (ApplicationImpl.Instance, "No file loaded", "No file is currently loaded", "Ok");
 
 
             return;
             return;
         }
         }
 
 
-        using var writer = new CsvWriter (
-                                          new StreamWriter (File.OpenWrite (_currentFile)),
-                                          CultureInfo.InvariantCulture
-                                         );
+        using CsvWriter writer = new (
+                                      new StreamWriter (File.OpenWrite (_currentFile)),
+                                      CultureInfo.InvariantCulture
+                                     );
 
 
         foreach (string col in _currentTable.Columns.Cast<DataColumn> ().Select (c => c.ColumnName))
         foreach (string col in _currentTable.Columns.Cast<DataColumn> ().Select (c => c.ColumnName))
         {
         {
@@ -555,7 +631,7 @@ public class CsvEditor : Scenario
 
 
         foreach (DataRow row in _currentTable.Rows)
         foreach (DataRow row in _currentTable.Rows)
         {
         {
-            foreach (object item in row.ItemArray)
+            foreach (object? item in row.ItemArray)
             {
             {
                 writer.WriteField (item);
                 writer.WriteField (item);
             }
             }
@@ -564,8 +640,13 @@ public class CsvEditor : Scenario
         }
         }
     }
     }
 
 
-    private void SelectedCellLabel_TextChanged (object sender, EventArgs e)
+    private void SelectedCellLabel_TextChanged (object? sender, EventArgs e)
     {
     {
+        if (_selectedCellTextField is null || _tableView is null)
+        {
+            return;
+        }
+
         // if user is in the text control and editing the selected cell
         // if user is in the text control and editing the selected cell
         if (!_selectedCellTextField.HasFocus)
         if (!_selectedCellTextField.HasFocus)
         {
         {
@@ -577,14 +658,14 @@ public class CsvEditor : Scenario
 
 
         if (match.Success)
         if (match.Success)
         {
         {
-            _tableView.SelectedColumn = int.Parse (match.Groups [1].Value);
-            _tableView.SelectedRow = int.Parse (match.Groups [2].Value);
+            _tableView.SelectedColumn = int.Parse (match.Groups [2].Value);
+            _tableView.SelectedRow = int.Parse (match.Groups [1].Value);
         }
         }
     }
     }
 
 
     private void SetFormat ()
     private void SetFormat ()
     {
     {
-        if (NoTableLoaded ())
+        if (NoTableLoaded () || _currentTable is null || _tableView is null)
         {
         {
             return;
             return;
         }
         }
@@ -593,7 +674,7 @@ public class CsvEditor : Scenario
 
 
         if (col.DataType == typeof (string))
         if (col.DataType == typeof (string))
         {
         {
-            MessageBox.ErrorQuery (
+            MessageBox.ErrorQuery (ApplicationImpl.Instance,
                                    "Cannot Format Column",
                                    "Cannot Format Column",
                                    "String columns cannot be Formatted, try adding a new column to the table with a date/numerical Type",
                                    "String columns cannot be Formatted, try adding a new column to the table with a date/numerical Type",
                                    "Ok"
                                    "Ok"
@@ -611,53 +692,26 @@ public class CsvEditor : Scenario
         }
         }
     }
     }
 
 
-    private void SetTable (DataTable dataTable) { _tableView.Table = new DataTableSource (_currentTable = dataTable); }
-
-    //private void SetupScrollBar ()
-    //{
-    //    var scrollBar = new ScrollBarView (_tableView, true);
-
-    //    scrollBar.ChangedPosition += (s, e) =>
-    //                                 {
-    //                                     _tableView.RowOffset = scrollBar.Position;
-
-    //                                     if (_tableView.RowOffset != scrollBar.Position)
-    //                                     {
-    //                                         scrollBar.Position = _tableView.RowOffset;
-    //                                     }
-
-    //                                     _tableView.SetNeedsDraw ();
-    //                                 };
-    //    /*
-    //    scrollBar.OtherScrollBarView.ChangedPosition += (s,e) => {
-    //        tableView.LeftItem = scrollBar.OtherScrollBarView.Position;
-    //        if (tableView.LeftItem != scrollBar.OtherScrollBarView.Position) {
-    //            scrollBar.OtherScrollBarView.Position = tableView.LeftItem;
-    //        }
-    //        tableView.SetNeedsDraw ();
-    //    };*/
-
-    //    _tableView.DrawingContent += (s, e) =>
-    //                              {
-    //                                  scrollBar.Size = _tableView.Table?.Rows ?? 0;
-    //                                  scrollBar.Position = _tableView.RowOffset;
-
-    //                                  //scrollBar.OtherScrollBarView.Size = tableView.Maxlength - 1;
-    //                                  //scrollBar.OtherScrollBarView.Position = tableView.LeftItem;
-    //                                  scrollBar.Refresh ();
-    //                              };
-    //}
+    private void SetTable (DataTable dataTable)
+    {
+        if (_tableView is null)
+        {
+            return;
+        }
+
+        _tableView.Table = new DataTableSource (_currentTable = dataTable);
+    }
 
 
     private void Sort (bool asc)
     private void Sort (bool asc)
     {
     {
-        if (NoTableLoaded ())
+        if (NoTableLoaded () || _currentTable is null || _tableView is null)
         {
         {
             return;
             return;
         }
         }
 
 
         if (_tableView.SelectedColumn == -1)
         if (_tableView.SelectedColumn == -1)
         {
         {
-            MessageBox.ErrorQuery ("No Column", "No column selected", "Ok");
+            MessageBox.ErrorQuery (ApplicationImpl.Instance, "No Column", "No column selected", "Ok");
 
 
             return;
             return;
         }
         }
@@ -668,9 +722,14 @@ public class CsvEditor : Scenario
         SetTable (_currentTable.DefaultView.ToTable ());
         SetTable (_currentTable.DefaultView.ToTable ());
     }
     }
 
 
-    private void TableViewKeyPress (object sender, Key e)
+    private void TableViewKeyPress (object? sender, Key e)
     {
     {
-        if (e.KeyCode == KeyCode.Delete)
+        if (_currentTable is null || _tableView is null)
+        {
+            return;
+        }
+
+        if (e.KeyCode == Key.Delete)
         {
         {
             if (_tableView.FullRowSelect)
             if (_tableView.FullRowSelect)
             {
             {

+ 8 - 2
Examples/UICatalog/Scenarios/Dialogs.cs

@@ -266,7 +266,7 @@ public class Dialogs : Scenario
             {
             {
                 Title = titleEdit.Text,
                 Title = titleEdit.Text,
                 Text = "Dialog Text",
                 Text = "Dialog Text",
-                ButtonAlignment = (Alignment)Enum.Parse (typeof (Alignment), alignmentGroup.Labels! [(int)alignmentGroup.Value!.Value] [1..]),
+                ButtonAlignment = (Alignment)Enum.Parse (typeof (Alignment), alignmentGroup.Labels! [(int)alignmentGroup.Value!.Value] [0..]),
 
 
                 Buttons = buttons.ToArray ()
                 Buttons = buttons.ToArray ()
             };
             };
@@ -340,7 +340,13 @@ public class Dialogs : Scenario
                               };
                               };
             dialog.Add (addChar);
             dialog.Add (addChar);
 
 
-            dialog.Closed += (s, e) => { buttonPressedLabel.Text = $"{clicked}"; };
+            dialog.IsRunningChanged += (s, e) =>
+                                       {
+                                           if (!e.Value)
+                                           {
+                                               buttonPressedLabel.Text = $"{clicked}";
+                                           }
+                                       };
         }
         }
         catch (FormatException)
         catch (FormatException)
         {
         {

+ 0 - 1413
Examples/UICatalog/Scenarios/DynamicMenuBar.cs

@@ -1,1413 +0,0 @@
-using System.Collections.ObjectModel;
-using System.ComponentModel;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Text;
-
-#pragma warning disable CS0618 // Type or member is obsolete
-
-namespace UICatalog.Scenarios;
-
-[ScenarioMetadata ("Dynamic MenuBar", "Demonstrates how to change a MenuBar dynamically.")]
-[ScenarioCategory ("Arrangement")]
-[ScenarioCategory ("Menus")]
-public class DynamicMenuBar : Scenario
-{
-    public override void Main ()
-    {
-        // Init
-        Application.Init ();
-
-        // Setup - Create a top-level application window and configure it.
-        DynamicMenuBarSample appWindow = new ()
-        {
-            Title = GetQuitKeyAndName ()
-        };
-
-        // Run - Start the application.
-        Application.Run (appWindow);
-        appWindow.Dispose ();
-
-        // Shutdown - Calling Application.Shutdown is required.
-        Application.Shutdown ();
-    }
-
-    public class Binding
-    {
-        private readonly PropertyInfo _sourceBindingProperty;
-        private readonly object _sourceDataContext;
-        private readonly IValueConverter _valueConverter;
-
-        public Binding (
-            View source,
-            string sourcePropertyName,
-            View target,
-            string targetPropertyName,
-            IValueConverter valueConverter = null
-        )
-        {
-            Target = target;
-            Source = source;
-            SourcePropertyName = sourcePropertyName;
-            TargetPropertyName = targetPropertyName;
-            _sourceDataContext = Source.GetType ().GetProperty ("DataContext").GetValue (Source);
-            _sourceBindingProperty = _sourceDataContext.GetType ().GetProperty (SourcePropertyName);
-            _valueConverter = valueConverter;
-            UpdateTarget ();
-
-            var notifier = (INotifyPropertyChanged)_sourceDataContext;
-
-            if (notifier != null)
-            {
-                notifier.PropertyChanged += (s, e) =>
-                                            {
-                                                if (e.PropertyName == SourcePropertyName)
-                                                {
-                                                    UpdateTarget ();
-                                                }
-                                            };
-            }
-        }
-
-        public View Source { get; }
-        public string SourcePropertyName { get; }
-        public View Target { get; }
-        public string TargetPropertyName { get; }
-
-        private void UpdateTarget ()
-        {
-            try
-            {
-                object sourceValue = _sourceBindingProperty.GetValue (_sourceDataContext);
-
-                if (sourceValue == null)
-                {
-                    return;
-                }
-
-                object finalValue = _valueConverter?.Convert (sourceValue) ?? sourceValue;
-
-                PropertyInfo targetProperty = Target.GetType ().GetProperty (TargetPropertyName);
-                targetProperty.SetValue (Target, finalValue);
-            }
-            catch (Exception ex)
-            {
-                MessageBox.ErrorQuery ("Binding Error", $"Binding failed: {ex}.", "Ok");
-            }
-        }
-    }
-
-    public class DynamicMenuBarDetails : FrameView
-    {
-        private bool _hasParent;
-        private MenuItem _menuItem;
-
-        public DynamicMenuBarDetails (MenuItem menuItem = null, bool hasParent = false) : this ()
-        {
-            _menuItem = menuItem;
-            _hasParent = hasParent;
-            Title = menuItem == null ? "Adding New Menu." : "Editing Menu.";
-        }
-
-        public DynamicMenuBarDetails ()
-        {
-            var lblTitle = new Label { Y = 1, Text = "Title:" };
-            Add (lblTitle);
-
-            TextTitle = new () { X = Pos.Right (lblTitle) + 2, Y = Pos.Top (lblTitle), Width = Dim.Fill () };
-            Add (TextTitle);
-
-            var lblHelp = new Label { X = Pos.Left (lblTitle), Y = Pos.Bottom (lblTitle) + 1, Text = "Help:" };
-            Add (lblHelp);
-
-            TextHelp = new () { X = Pos.Left (TextTitle), Y = Pos.Top (lblHelp), Width = Dim.Fill () };
-            Add (TextHelp);
-
-            var lblAction = new Label { X = Pos.Left (lblTitle), Y = Pos.Bottom (lblHelp) + 1, Text = "Action:" };
-            Add (lblAction);
-
-            TextAction = new ()
-            {
-                X = Pos.Left (TextTitle), Y = Pos.Top (lblAction), Width = Dim.Fill (), Height = 5
-            };
-            Add (TextAction);
-
-            var lblHotKey = new Label { X = Pos.Left (lblTitle), Y = Pos.Bottom (lblAction) + 5, Text = "HotKey:" };
-            Add (lblHotKey);
-
-            TextHotKey = new ()
-            {
-                X = Pos.Left (TextTitle), Y = Pos.Bottom (lblAction) + 5, Width = 2, ReadOnly = true
-            };
-
-            TextHotKey.TextChanging += (s, e) =>
-                                       {
-                                           if (!string.IsNullOrEmpty (e.Result) && char.IsLower (e.Result [0]))
-                                           {
-                                               e.Result = e.Result.ToUpper ();
-                                           }
-                                       };
-            TextHotKey.TextChanged += (s, _) => TextHotKey.SelectAll ();
-            TextHotKey.SelectAll ();
-            Add (TextHotKey);
-
-            CkbIsTopLevel = new ()
-            {
-                X = Pos.Left (lblTitle), Y = Pos.Bottom (lblHotKey) + 1, Text = "IsTopLevel"
-            };
-            Add (CkbIsTopLevel);
-
-            CkbSubMenu = new ()
-            {
-                X = Pos.Left (lblTitle),
-                Y = Pos.Bottom (CkbIsTopLevel),
-                CheckedState = (_menuItem == null ? !_hasParent : HasSubMenus (_menuItem)) ? CheckState.Checked : CheckState.UnChecked,
-                Text = "Has sub-menus"
-            };
-            Add (CkbSubMenu);
-
-            CkbNullCheck = new ()
-            {
-                X = Pos.Left (lblTitle), Y = Pos.Bottom (CkbSubMenu), Text = "Allow null checked"
-            };
-            Add (CkbNullCheck);
-
-            var rChkLabels = new [] { "NoCheck", "Checked", "Radio" };
-
-            OsChkStyle = new ()
-            {
-                X = Pos.Left (lblTitle), Y = Pos.Bottom (CkbSubMenu) + 1, Labels = rChkLabels
-            };
-            Add (OsChkStyle);
-
-            var lblShortcut = new Label
-            {
-                X = Pos.Right (CkbSubMenu) + 10, Y = Pos.Top (CkbSubMenu), Text = "Shortcut:"
-            };
-            Add (lblShortcut);
-
-            TextShortcutKey = new ()
-            {
-                X = Pos.X (lblShortcut), Y = Pos.Bottom (lblShortcut), Width = Dim.Fill (), ReadOnly = true
-            };
-
-            TextShortcutKey.KeyDown += (s, e) =>
-                                    {
-                                        TextShortcutKey.Text = e.ToString ();
-
-                                    };
-
-            Add (TextShortcutKey);
-
-            var btnShortcut = new Button
-            {
-                X = Pos.X (lblShortcut), Y = Pos.Bottom (TextShortcutKey) + 1, Text = "Clear Shortcut"
-            };
-            btnShortcut.Accepting += (s, e) => { TextShortcutKey.Text = ""; };
-            Add (btnShortcut);
-
-            CkbIsTopLevel.CheckedStateChanging += (s, e) =>
-                                     {
-                                         if ((_menuItem != null && _menuItem.Parent != null && e.Result == CheckState.Checked)
-                                             || (_menuItem == null && _hasParent && e.Result == CheckState.Checked))
-                                         {
-                                             MessageBox.ErrorQuery (
-                                                                    "Invalid IsTopLevel",
-                                                                    "Only menu bar can have top level menu item!",
-                                                                    "Ok"
-                                                                   );
-                                             e.Handled = true;
-
-                                             return;
-                                         }
-
-                                         if (e.Result == CheckState.Checked)
-                                         {
-                                             CkbSubMenu.CheckedState = CheckState.UnChecked;
-                                             CkbSubMenu.SetNeedsDraw ();
-                                             TextHelp.Enabled = true;
-                                             TextAction.Enabled = true;
-                                             TextShortcutKey.Enabled = true;
-                                         }
-                                         else
-                                         {
-                                             if ((_menuItem == null && !_hasParent) || _menuItem.Parent == null)
-                                             {
-                                                 CkbSubMenu.CheckedState = CheckState.Checked;
-                                                 CkbSubMenu.SetNeedsDraw ();
-                                                 TextShortcutKey.Enabled = false;
-                                             }
-
-                                             TextHelp.Text = "";
-                                             TextHelp.Enabled = false;
-                                             TextAction.Text = "";
-
-                                             TextShortcutKey.Enabled =
-                                                 e.Result == CheckState.Checked && CkbSubMenu.CheckedState == CheckState.UnChecked;
-                                         }
-                                     };
-
-            CkbSubMenu.CheckedStateChanged += (s, e) =>
-                                  {
-                                      if (e.Value == CheckState.Checked)
-                                      {
-                                          CkbIsTopLevel.CheckedState = CheckState.UnChecked;
-                                          CkbIsTopLevel.SetNeedsDraw ();
-                                          TextHelp.Text = "";
-                                          TextHelp.Enabled = false;
-                                          TextAction.Text = "";
-                                          TextAction.Enabled = false;
-                                          TextShortcutKey.Text = "";
-                                          TextShortcutKey.Enabled = false;
-                                      }
-                                      else
-                                      {
-                                          if (!_hasParent)
-                                          {
-                                              CkbIsTopLevel.CheckedState = CheckState.Checked;
-                                              CkbIsTopLevel.SetNeedsDraw ();
-                                              TextShortcutKey.Enabled = true;
-                                          }
-
-                                          TextHelp.Enabled = true;
-                                          TextAction.Enabled = true;
-
-                                          if (_hasParent)
-                                          {
-                                              TextShortcutKey.Enabled = CkbIsTopLevel.CheckedState == CheckState.UnChecked
-                                                                     && e.Value == CheckState.UnChecked;
-                                          }
-                                      }
-                                  };
-
-            CkbNullCheck.CheckedStateChanged += (s, e) =>
-                                    {
-                                        if (_menuItem != null)
-                                        {
-                                            _menuItem.AllowNullChecked = e.Value == CheckState.Checked;
-                                        }
-                                    };
-
-            //Add (_frmMenuDetails);
-        }
-
-        public CheckBox CkbIsTopLevel { get; }
-        public CheckBox CkbNullCheck { get; }
-        public CheckBox CkbSubMenu { get; }
-        public OptionSelector OsChkStyle { get; }
-        public TextView TextAction { get; }
-        public TextField TextHelp { get; }
-        public TextField TextHotKey { get; }
-        public TextField TextShortcutKey { get; }
-        public TextField TextTitle { get; }
-
-        public Action CreateAction (MenuItem menuItem, DynamicMenuItem item)
-        {
-            switch (menuItem.CheckType)
-            {
-                case MenuItemCheckStyle.NoCheck:
-                    return () => MessageBox.ErrorQuery (item.Title, item.Action, "Ok");
-                case MenuItemCheckStyle.Checked:
-                    return menuItem.ToggleChecked;
-                case MenuItemCheckStyle.Radio:
-                    break;
-            }
-
-            return () =>
-                   {
-                       menuItem.Checked = true;
-                       var parent = menuItem?.Parent as MenuBarItem;
-
-                       if (parent != null)
-                       {
-                           MenuItem [] childrens = parent.Children;
-
-                           for (var i = 0; i < childrens.Length; i++)
-                           {
-                               MenuItem child = childrens [i];
-
-                               if (child != menuItem)
-                               {
-                                   child.Checked = false;
-                               }
-                           }
-                       }
-                   };
-        }
-
-        public void EditMenuBarItem (MenuItem menuItem)
-        {
-            if (menuItem == null)
-            {
-                _hasParent = false;
-                Enabled = false;
-                CleanEditMenuBarItem ();
-
-                return;
-            }
-
-            _hasParent = menuItem.Parent != null;
-            Enabled = true;
-            _menuItem = menuItem;
-            TextTitle.Text = menuItem?.Title ?? "";
-            TextHelp.Text = menuItem?.Help ?? "";
-
-            TextAction.Text = menuItem.Action != null
-                                  ? GetTargetAction (menuItem.Action)
-                                  : string.Empty;
-            TextHotKey.Text = menuItem?.HotKey != Key.Empty ? menuItem.HotKey.ToString () : "";
-            CkbIsTopLevel.CheckedState = IsTopLevel (menuItem) ? CheckState.Checked : CheckState.UnChecked;
-            CkbSubMenu.CheckedState = HasSubMenus (menuItem) ? CheckState.Checked : CheckState.UnChecked;
-            CkbNullCheck.CheckedState = menuItem.AllowNullChecked ? CheckState.Checked : CheckState.UnChecked;
-            TextHelp.Enabled = CkbSubMenu.CheckedState == CheckState.UnChecked;
-            TextAction.Enabled = CkbSubMenu.CheckedState == CheckState.UnChecked;
-            OsChkStyle.Value = (int)(menuItem?.CheckType ?? MenuItemCheckStyle.NoCheck);
-            TextShortcutKey.Text = menuItem?.ShortcutTag ?? "";
-
-            TextShortcutKey.Enabled = CkbIsTopLevel.CheckedState == CheckState.Checked && CkbSubMenu.CheckedState == CheckState.UnChecked
-                                   || CkbIsTopLevel.CheckedState == CheckState.UnChecked && CkbSubMenu.CheckedState == CheckState.UnChecked;
-        }
-
-        public DynamicMenuItem EnterMenuItem ()
-        {
-            var valid = false;
-
-            if (_menuItem == null)
-            {
-                var m = new DynamicMenuItem ();
-                TextTitle.Text = m.Title;
-                TextHelp.Text = m.Help;
-                TextAction.Text = m.Action;
-                TextHotKey.Text = m.HotKey ?? string.Empty;
-                CkbIsTopLevel.CheckedState = CheckState.UnChecked;
-                CkbSubMenu.CheckedState = !_hasParent ? CheckState.Checked : CheckState.UnChecked;
-                CkbNullCheck.CheckedState = CheckState.UnChecked;
-                TextHelp.Enabled = _hasParent;
-                TextAction.Enabled = _hasParent;
-                TextShortcutKey.Enabled = _hasParent;
-            }
-            else
-            {
-                EditMenuBarItem (_menuItem);
-            }
-
-            var btnOk = new Button { IsDefault = true, Text = "Ok" };
-
-            btnOk.Accepting += (s, e) =>
-                            {
-                                if (string.IsNullOrEmpty (TextTitle.Text))
-                                {
-                                    MessageBox.ErrorQuery ("Invalid title", "Must enter a valid title!.", "Ok");
-                                }
-                                else
-                                {
-                                    valid = true;
-                                    Application.RequestStop ();
-                                }
-                            };
-            var btnCancel = new Button { Text = "Cancel" };
-
-            btnCancel.Accepting += (s, e) =>
-                                {
-                                    TextTitle.Text = string.Empty;
-                                    Application.RequestStop ();
-                                };
-
-            var dialog = new Dialog
-                { Title = "Enter the menu details.", Buttons = [btnOk, btnCancel], Height = Dim.Auto (DimAutoStyle.Content, 23, Application.Screen.Height) };
-
-            Width = Dim.Fill ();
-            Height = Dim.Fill () - 2;
-            dialog.Add (this);
-            TextTitle.SetFocus ();
-            TextTitle.CursorPosition = TextTitle.Text.Length;
-            Application.Run (dialog);
-            dialog.Dispose ();
-
-            if (valid)
-            {
-                return new ()
-                {
-                    Title = TextTitle.Text,
-                    Help = TextHelp.Text,
-                    Action = TextAction.Text,
-                    HotKey = TextHotKey.Text,
-                    IsTopLevel = CkbIsTopLevel?.CheckedState == CheckState.Checked,
-                    HasSubMenu = CkbSubMenu?.CheckedState == CheckState.Checked,
-                    CheckStyle = OsChkStyle.Value == 0 ? MenuItemCheckStyle.NoCheck :
-                                 OsChkStyle.Value == 1 ? MenuItemCheckStyle.Checked :
-                                 MenuItemCheckStyle.Radio,
-                    ShortcutKey = TextShortcutKey.Text,
-                    AllowNullChecked = CkbNullCheck?.CheckedState == CheckState.Checked,
-                };
-            }
-
-            return null;
-        }
-
-        public void UpdateParent (ref MenuItem menuItem)
-        {
-            var parent = menuItem.Parent as MenuBarItem;
-            int idx = parent.GetChildrenIndex (menuItem);
-
-            if (!(menuItem is MenuBarItem))
-            {
-                menuItem = new MenuBarItem (menuItem.Title, new MenuItem [] { }, menuItem.Parent);
-
-                if (idx > -1)
-                {
-                    parent.Children [idx] = menuItem;
-                }
-            }
-            else
-            {
-                menuItem = new (
-                                menuItem.Title,
-                                menuItem.Help,
-                                CreateAction (menuItem, new ()),
-                                null,
-                                menuItem.Parent
-                               );
-
-                if (idx > -1)
-                {
-                    parent.Children [idx] = menuItem;
-                }
-            }
-        }
-
-        private void CleanEditMenuBarItem ()
-        {
-            TextTitle.Text = "";
-            TextHelp.Text = "";
-            TextAction.Text = "";
-            TextHotKey.Text = "";
-            CkbIsTopLevel.CheckedState = CheckState.UnChecked;
-            CkbSubMenu.CheckedState = CheckState.UnChecked;
-            OsChkStyle.Value = (int)MenuItemCheckStyle.NoCheck;
-            TextShortcutKey.Text = "";
-        }
-
-        private string GetTargetAction (Action action)
-        {
-            object me = action.Target;
-
-            if (me == null)
-            {
-                throw new ArgumentException ();
-            }
-
-            var v = new object ();
-
-            foreach (FieldInfo field in me.GetType ().GetFields ())
-            {
-                if (field.Name == "item")
-                {
-                    v = field.GetValue (me);
-                }
-            }
-
-            return v == null || !(v is DynamicMenuItem item) ? string.Empty : item.Action;
-        }
-
-        private bool HasSubMenus (MenuItem menuItem)
-        {
-            var menuBarItem = menuItem as MenuBarItem;
-
-            if (menuBarItem != null && menuBarItem.Children != null && (menuBarItem.Children.Length > 0 || menuBarItem.Action == null))
-            {
-                return true;
-            }
-
-            return false;
-        }
-
-        private bool IsTopLevel (MenuItem menuItem)
-        {
-            var topLevel = menuItem as MenuBarItem;
-
-            if (topLevel != null && topLevel.Parent == null && (topLevel.Children == null || topLevel.Children.Length == 0) && topLevel.Action != null)
-            {
-                return true;
-            }
-
-            return false;
-        }
-    }
-
-    public class DynamicMenuBarSample : Window
-    {
-        private readonly ListView _lstMenus;
-        private MenuItem _currentEditMenuBarItem;
-        private MenuItem _currentMenuBarItem;
-        private int _currentSelectedMenuBar;
-        private MenuBar _menuBar;
-
-        public DynamicMenuBarSample ()
-        {
-            DataContext = new ();
-
-            var frmDelimiter = new FrameView
-            {
-                X = Pos.Center (),
-                Y = 3,
-                Width = 25,
-                Height = 4,
-                Title = "Shortcut Delimiter:"
-            };
-
-            var txtDelimiter = new TextField
-            {
-                X = Pos.Center (), Width = 2, Text = Key.Separator.ToString ()
-            };
-
-
-            var frmMenu = new FrameView { Y = 7, Width = Dim.Percent (50), Height = Dim.Fill (), Title = "Menus:" };
-
-            var btnAddMenuBar = new Button { Y = 1, Text = "Add a MenuBar" };
-            frmMenu.Add (btnAddMenuBar);
-
-            var btnMenuBarUp = new Button { X = Pos.Center (), Text = Glyphs.UpArrow.ToString () };
-            frmMenu.Add (btnMenuBarUp);
-
-            var btnMenuBarDown = new Button { X = Pos.Center (), Y = Pos.Bottom (btnMenuBarUp), Text = Glyphs.DownArrow.ToString () };
-            frmMenu.Add (btnMenuBarDown);
-
-            var btnRemoveMenuBar = new Button { Y = 1, Text = "Remove a MenuBar" };
-
-            btnRemoveMenuBar.X = Pos.AnchorEnd (0) - (Pos.Right (btnRemoveMenuBar) - Pos.Left (btnRemoveMenuBar));
-            frmMenu.Add (btnRemoveMenuBar);
-
-            var btnPrevious = new Button
-            {
-                X = Pos.Left (btnAddMenuBar), Y = Pos.Top (btnAddMenuBar) + 2, Text = Glyphs.LeftArrow.ToString ()
-            };
-            frmMenu.Add (btnPrevious);
-
-            var btnAdd = new Button { Y = Pos.Top (btnPrevious) + 2, Text = " Add  " };
-            btnAdd.X = Pos.AnchorEnd ();
-            frmMenu.Add (btnAdd);
-
-            var btnNext = new Button { X = Pos.X (btnAdd), Y = Pos.Top (btnPrevious), Text = Glyphs.RightArrow.ToString () };
-            frmMenu.Add (btnNext);
-
-            var lblMenuBar = new Label
-            {
-                SchemeName = "Dialog",
-                TextAlignment = Alignment.Center,
-                X = Pos.Right (btnPrevious) + 1,
-                Y = Pos.Top (btnPrevious),
-
-                Width = Dim.Fill () - Dim.Func (_ => btnAdd.Frame.Width + 1),
-                Height = 1
-            };
-
-            lblMenuBar.TextChanged += (s, e) =>
-                                       {
-                                           if (lblMenuBar.Text.Contains ("_"))
-                                           {
-                                               lblMenuBar.Text = lblMenuBar.Text.Replace ("_", "");
-                                           }
-                                       };
-            frmMenu.Add (lblMenuBar);
-            lblMenuBar.WantMousePositionReports = true;
-            lblMenuBar.CanFocus = true;
-
-            var lblParent = new Label
-            {
-                TextAlignment = Alignment.Center,
-                X = Pos.Right (btnPrevious) + 1,
-                Y = Pos.Top (btnPrevious) + 1,
-
-                Width = Dim.Fill () - Dim.Width (btnAdd) - 1
-            };
-            frmMenu.Add (lblParent);
-
-            var btnPreviowsParent = new Button
-            {
-                X = Pos.Left (btnAddMenuBar), Y = Pos.Top (btnPrevious) + 1, Text = ".."
-            };
-            frmMenu.Add (btnPreviowsParent);
-
-            _lstMenus = new ()
-            {
-                SchemeName = "Dialog",
-                X = Pos.Right (btnPrevious) + 1,
-                Y = Pos.Top (btnPrevious) + 2,
-                Width = lblMenuBar.Width,
-                Height = Dim.Fill (),
-                Source = new ListWrapper<DynamicMenuItemList> ([])
-            };
-            frmMenu.Add (_lstMenus);
-
-            //lblMenuBar.TabIndex = btnPrevious.TabIndex + 1;
-            //_lstMenus.TabIndex = lblMenuBar.TabIndex + 1;
-            //btnNext.TabIndex = _lstMenus.TabIndex + 1;
-            //btnAdd.TabIndex = btnNext.TabIndex + 1;
-
-            var btnRemove = new Button { X = Pos.Left (btnAdd), Y = Pos.Top (btnAdd) + 1, Text = "Remove" };
-            frmMenu.Add (btnRemove);
-
-            var btnUp = new Button { X = Pos.Right (_lstMenus) + 2, Y = Pos.Top (btnRemove) + 2, Text = Glyphs.UpArrow.ToString () };
-            frmMenu.Add (btnUp);
-
-            var btnDown = new Button { X = Pos.Right (_lstMenus) + 2, Y = Pos.Top (btnUp) + 1, Text = Glyphs.DownArrow.ToString () };
-            frmMenu.Add (btnDown);
-
-            Add (frmMenu);
-
-            var frmMenuDetails = new DynamicMenuBarDetails
-            {
-                X = Pos.Right (frmMenu),
-                Y = Pos.Top (frmMenu),
-                Width = Dim.Fill (),
-                Height = Dim.Fill (2),
-                Title = "Menu Details:"
-            };
-            Add (frmMenuDetails);
-
-            btnMenuBarUp.Accepting += (s, e) =>
-                                    {
-                                        int i = _currentSelectedMenuBar;
-
-                                        MenuBarItem menuItem = _menuBar != null && _menuBar.Menus.Length > 0
-                                                                   ? _menuBar.Menus [i]
-                                                                   : null;
-
-                                        if (menuItem != null)
-                                        {
-                                            MenuBarItem [] menus = _menuBar.Menus;
-
-                                            if (i > 0)
-                                            {
-                                                menus [i] = menus [i - 1];
-                                                menus [i - 1] = menuItem;
-                                                _currentSelectedMenuBar = i - 1;
-                                                _menuBar.SetNeedsDraw ();
-                                            }
-                                        }
-                                    };
-
-            btnMenuBarDown.Accepting += (s, e) =>
-                                      {
-                                          int i = _currentSelectedMenuBar;
-
-                                          MenuBarItem menuItem = _menuBar != null && _menuBar.Menus.Length > 0
-                                                                     ? _menuBar.Menus [i]
-                                                                     : null;
-
-                                          if (menuItem != null)
-                                          {
-                                              MenuBarItem [] menus = _menuBar.Menus;
-
-                                              if (i < menus.Length - 1)
-                                              {
-                                                  menus [i] = menus [i + 1];
-                                                  menus [i + 1] = menuItem;
-                                                  _currentSelectedMenuBar = i + 1;
-                                                  _menuBar.SetNeedsDraw ();
-                                              }
-                                          }
-                                      };
-
-            btnUp.Accepting += (s, e) =>
-                             {
-                                 int i = _lstMenus.SelectedItem.Value;
-                                 MenuItem menuItem = DataContext.Menus.Count > 0 ? DataContext.Menus [i].MenuItem : null;
-
-                                 if (menuItem != null)
-                                 {
-                                     MenuItem [] childrens = ((MenuBarItem)_currentMenuBarItem).Children;
-
-                                     if (i > 0)
-                                     {
-                                         childrens [i] = childrens [i - 1];
-                                         childrens [i - 1] = menuItem;
-                                         DataContext.Menus [i] = DataContext.Menus [i - 1];
-
-                                         DataContext.Menus [i - 1] =
-                                             new () { Title = menuItem.Title, MenuItem = menuItem };
-                                         _lstMenus.SelectedItem = i - 1;
-                                     }
-                                 }
-                             };
-
-            btnDown.Accepting += (s, e) =>
-                               {
-                                   int i = _lstMenus.SelectedItem.Value;
-                                   MenuItem menuItem = DataContext.Menus.Count > 0 ? DataContext.Menus [i].MenuItem : null;
-
-                                   if (menuItem != null)
-                                   {
-                                       MenuItem [] childrens = ((MenuBarItem)_currentMenuBarItem).Children;
-
-                                       if (i < childrens.Length - 1)
-                                       {
-                                           childrens [i] = childrens [i + 1];
-                                           childrens [i + 1] = menuItem;
-                                           DataContext.Menus [i] = DataContext.Menus [i + 1];
-
-                                           DataContext.Menus [i + 1] =
-                                               new () { Title = menuItem.Title, MenuItem = menuItem };
-                                           _lstMenus.SelectedItem = i + 1;
-                                       }
-                                   }
-                               };
-
-            btnPreviowsParent.Accepting += (s, e) =>
-                                         {
-                                             if (_currentMenuBarItem != null && _currentMenuBarItem.Parent != null)
-                                             {
-                                                 MenuItem mi = _currentMenuBarItem;
-                                                 _currentMenuBarItem = _currentMenuBarItem.Parent as MenuBarItem;
-                                                 SetListViewSource (_currentMenuBarItem, true);
-                                                 int i = ((MenuBarItem)_currentMenuBarItem).GetChildrenIndex (mi);
-
-                                                 if (i > -1)
-                                                 {
-                                                     _lstMenus.SelectedItem = i;
-                                                 }
-
-                                                 if (_currentMenuBarItem.Parent != null)
-                                                 {
-                                                     DataContext.Parent = _currentMenuBarItem.Title;
-                                                 }
-                                                 else
-                                                 {
-                                                     DataContext.Parent = string.Empty;
-                                                 }
-                                             }
-                                             else
-                                             {
-                                                 DataContext.Parent = string.Empty;
-                                             }
-                                         };
-
-            var btnOk = new Button { X = Pos.Right (frmMenu) + 20, Y = Pos.Bottom (frmMenuDetails), Text = "Ok" };
-            Add (btnOk);
-
-            var btnCancel = new Button { X = Pos.Right (btnOk) + 3, Y = Pos.Top (btnOk), Text = "Cancel" };
-            btnCancel.Accepting += (s, e) => { SetFrameDetails (_currentEditMenuBarItem); };
-            Add (btnCancel);
-
-            txtDelimiter.TextChanging += (s, e) =>
-                                          {
-                                              if (!string.IsNullOrEmpty (e.Result))
-                                              {
-                                                  Key.Separator = e.Result.ToRunes () [0];
-                                              }
-                                              else
-                                              {
-                                                  e.Handled = true;
-                                                  txtDelimiter.SelectAll ();
-                                              }
-                                          };
-            txtDelimiter.TextChanged += (s, _) =>
-                                         {
-                                             txtDelimiter.SelectAll ();
-                                             SetFrameDetails ();
-                                         };
-            frmDelimiter.Add (txtDelimiter);
-            txtDelimiter.SelectAll ();
-            Add (frmDelimiter);
-
-            _lstMenus.SelectedItemChanged += (s, e) => { SetFrameDetails (); };
-
-            btnOk.Accepting += (s, e) =>
-                             {
-                                 if (string.IsNullOrEmpty (frmMenuDetails.TextTitle.Text) && _currentEditMenuBarItem != null)
-                                 {
-                                     MessageBox.ErrorQuery ("Invalid title", "Must enter a valid title!.", "Ok");
-                                 }
-                                 else if (_currentEditMenuBarItem != null)
-                                 {
-                                     var menuItem = new DynamicMenuItem
-                                     {
-                                         Title = frmMenuDetails.TextTitle.Text,
-                                         Help = frmMenuDetails.TextHelp.Text,
-                                         Action = frmMenuDetails.TextAction.Text,
-                                         HotKey = frmMenuDetails.TextHotKey.Text,
-                                         IsTopLevel = frmMenuDetails.CkbIsTopLevel?.CheckedState == CheckState.Checked,
-                                         HasSubMenu = frmMenuDetails.CkbSubMenu?.CheckedState == CheckState.Checked,
-                                         CheckStyle = frmMenuDetails.OsChkStyle.Value == 0
-                                                          ? MenuItemCheckStyle.NoCheck
-                                                          : frmMenuDetails.OsChkStyle.Value == 1
-                                                              ? MenuItemCheckStyle.Checked
-                                                              : MenuItemCheckStyle.Radio,
-                                         ShortcutKey = frmMenuDetails.TextShortcutKey.Text
-                                     };
-                                     UpdateMenuItem (_currentEditMenuBarItem, menuItem, _lstMenus.SelectedItem.Value);
-                                 }
-                             };
-
-            btnAdd.Accepting += (s, e) =>
-                              {
-                                  if (MenuBar == null)
-                                  {
-                                      MessageBox.ErrorQuery ("Menu Bar Error", "Must add a MenuBar first!", "Ok");
-                                      btnAddMenuBar.SetFocus ();
-
-                                      return;
-                                  }
-
-                                  var frameDetails = new DynamicMenuBarDetails (null, _currentMenuBarItem != null);
-                                  DynamicMenuItem item = frameDetails.EnterMenuItem ();
-
-                                  if (item == null)
-                                  {
-                                      return;
-                                  }
-
-                                  if (_currentMenuBarItem is not MenuBarItem)
-                                  {
-                                      var parent = _currentMenuBarItem.Parent as MenuBarItem;
-                                      int idx = parent.GetChildrenIndex (_currentMenuBarItem);
-
-                                      _currentMenuBarItem = new MenuBarItem (
-                                                                             _currentMenuBarItem.Title,
-                                                                             new MenuItem [] { },
-                                                                             _currentMenuBarItem.Parent
-                                                                            );
-                                      _currentMenuBarItem.CheckType = item.CheckStyle;
-                                      parent.Children [idx] = _currentMenuBarItem;
-                                  }
-                                  else
-                                  {
-                                      MenuItem newMenu = CreateNewMenu (item, _currentMenuBarItem);
-                                      var menuBarItem = _currentMenuBarItem as MenuBarItem;
-                                      menuBarItem.AddMenuBarItem (MenuBar, newMenu);
-
-
-                                      DataContext.Menus.Add (new () { Title = newMenu.Title, MenuItem = newMenu });
-                                      _lstMenus.MoveDown ();
-                                  }
-                              };
-
-            btnRemove.Accepting += (s, e) =>
-                                {
-                                    MenuItem menuItem = (DataContext.Menus.Count > 0 && _lstMenus.SelectedItem is {} selectedItem
-                                                             ? DataContext.Menus [selectedItem].MenuItem
-                                                             : _currentEditMenuBarItem);
-
-                                    if (menuItem != null)
-                                    {
-                                        menuItem.RemoveMenuItem ();
-
-                                        if (_currentEditMenuBarItem == menuItem)
-                                        {
-                                            _currentEditMenuBarItem = null;
-
-                                            if (menuItem.Parent is null)
-                                            {
-                                                _currentSelectedMenuBar = Math.Max (Math.Min (_currentSelectedMenuBar, _menuBar.Menus.Length - 1), 0);
-                                            }
-
-                                            SelectCurrentMenuBarItem ();
-                                        }
-
-                                        if (_lstMenus.SelectedItem is {} selected)
-                                        {
-                                            DataContext.Menus?.RemoveAt (selected);
-                                        }
-
-                                        if (_lstMenus.Source.Count > 0 && _lstMenus.SelectedItem > _lstMenus.Source.Count - 1)
-                                        {
-                                            _lstMenus.SelectedItem = _lstMenus.Source.Count - 1;
-                                        }
-
-                                        if (_menuBar.Menus.Length == 0)
-                                        {
-                                            RemoveMenuBar ();
-                                        }
-
-                                        _lstMenus.SetNeedsDraw ();
-                                        SetFrameDetails ();
-                                    }
-                                };
-
-            _lstMenus.OpenSelectedItem += (s, e) =>
-                                          {
-                                              _currentMenuBarItem = DataContext.Menus [e.Item.Value].MenuItem;
-
-                                              if (!(_currentMenuBarItem is MenuBarItem))
-                                              {
-                                                  MessageBox.ErrorQuery ("Menu Open Error", "Must allows sub menus first!", "Ok");
-
-                                                  return;
-                                              }
-
-                                              DataContext.Parent = _currentMenuBarItem.Title;
-                                              DataContext.Menus = new ();
-                                              SetListViewSource (_currentMenuBarItem, true);
-                                              MenuItem menuBarItem = DataContext.Menus.Count > 0 ? DataContext.Menus [0].MenuItem : null;
-                                              SetFrameDetails (menuBarItem);
-                                          };
-
-            _lstMenus.HasFocusChanging += (s, e) =>
-                               {
-                                   MenuItem menuBarItem = _lstMenus.SelectedItem is {} selectedItem && DataContext.Menus.Count > 0
-                                                              ? DataContext.Menus [selectedItem].MenuItem
-                                                              : null;
-                                   SetFrameDetails (menuBarItem);
-                               };
-
-            btnNext.Accepting += (s, e) =>
-                               {
-                                   if (_menuBar != null && _currentSelectedMenuBar + 1 < _menuBar.Menus.Length)
-                                   {
-                                       _currentSelectedMenuBar++;
-                                   }
-
-                                   SelectCurrentMenuBarItem ();
-                               };
-
-            btnPrevious.Accepting += (s, e) =>
-                                   {
-                                       if (_currentSelectedMenuBar - 1 > -1)
-                                       {
-                                           _currentSelectedMenuBar--;
-                                       }
-
-                                       SelectCurrentMenuBarItem ();
-                                   };
-
-            lblMenuBar.HasFocusChanging += (s, e) =>
-                                 {
-                                     if (_menuBar?.Menus != null)
-                                     {
-                                         _currentMenuBarItem = _menuBar.Menus [_currentSelectedMenuBar];
-                                         SetFrameDetails (_menuBar.Menus [_currentSelectedMenuBar]);
-                                     }
-                                 };
-
-            btnAddMenuBar.Accepting += (s, e) =>
-                                     {
-                                         var frameDetails = new DynamicMenuBarDetails (null);
-                                         DynamicMenuItem item = frameDetails.EnterMenuItem ();
-
-                                         if (item == null)
-                                         {
-                                             return;
-                                         }
-
-                                         if (MenuBar == null)
-                                         {
-                                             _menuBar = new ();
-                                             Add (_menuBar);
-                                         }
-
-                                         var newMenu = CreateNewMenu (item) as MenuBarItem;
-                                         newMenu.AddMenuBarItem (MenuBar);
-
-                                         _currentMenuBarItem = newMenu;
-                                         _currentMenuBarItem.CheckType = item.CheckStyle;
-
-                                         if (Key.TryParse (item.ShortcutKey, out Key key))
-                                         {
-                                             _currentMenuBarItem.ShortcutKey = key;
-                                         }
-
-                                         _currentSelectedMenuBar = _menuBar.Menus.Length - 1;
-                                         _menuBar.Menus [_currentSelectedMenuBar] = newMenu;
-                                         lblMenuBar.Text = newMenu.Title;
-                                         SetListViewSource (_currentMenuBarItem, true);
-                                         SetFrameDetails (_menuBar.Menus [_currentSelectedMenuBar]);
-                                         _menuBar.SetNeedsDraw ();
-                                     };
-
-            btnRemoveMenuBar.Accepting += (s, e) =>
-                                        {
-                                            if (_menuBar == null)
-                                            {
-                                                return;
-                                            }
-
-                                            if (_menuBar != null && _menuBar.Menus.Length > 0)
-                                            {
-                                                _currentMenuBarItem.RemoveMenuItem ();
-
-
-
-                                                if (_currentSelectedMenuBar - 1 >= 0 && _menuBar.Menus.Length > 0)
-                                                {
-                                                    _currentSelectedMenuBar--;
-                                                }
-
-                                                _currentMenuBarItem = _menuBar.Menus?.Length > 0
-                                                                          ? _menuBar.Menus [_currentSelectedMenuBar]
-                                                                          : null;
-                                            }
-
-                                            RemoveMenuBar ();
-
-                                            SetListViewSource (_currentMenuBarItem, true);
-                                            SetFrameDetails ();
-                                        };
-
-            void RemoveMenuBar ()
-            {
-                if (MenuBar != null && _currentMenuBarItem == null && _menuBar.Menus.Length == 0)
-                {
-                    Remove (_menuBar);
-                    _menuBar.Dispose ();
-                    _menuBar = null;
-                    DataContext.Menus = new ();
-                    _currentMenuBarItem = null;
-                    _currentSelectedMenuBar = -1;
-                    lblMenuBar.Text = string.Empty;
-                }
-                else
-                {
-                    lblMenuBar.Text = _menuBar.Menus [_currentSelectedMenuBar].Title;
-                }
-            }
-
-            SetFrameDetails ();
-
-            var ustringConverter = new UStringValueConverter ();
-            ListWrapperConverter<DynamicMenuItemList> listWrapperConverter = new ListWrapperConverter<DynamicMenuItemList> ();
-
-            var bdgMenuBar = new Binding (this, "MenuBar", lblMenuBar, "Text", ustringConverter);
-            var bdgParent = new Binding (this, "Parent", lblParent, "Text", ustringConverter);
-            var bdgMenus = new Binding (this, "Menus", _lstMenus, "Source", listWrapperConverter);
-
-            void SetFrameDetails (MenuItem menuBarItem = null)
-            {
-                MenuItem menuItem;
-
-                if (menuBarItem == null)
-                {
-                    menuItem = _lstMenus.SelectedItem is {} selectedItem && DataContext.Menus.Count > 0
-                                   ? DataContext.Menus [selectedItem].MenuItem
-                                   : _currentEditMenuBarItem;
-                }
-                else
-                {
-                    menuItem = menuBarItem;
-                }
-
-                _currentEditMenuBarItem = menuItem;
-                frmMenuDetails.EditMenuBarItem (menuItem);
-                bool f = btnOk.Enabled == frmMenuDetails.Enabled;
-
-                if (!f)
-                {
-                    btnOk.Enabled = frmMenuDetails.Enabled;
-                    btnCancel.Enabled = frmMenuDetails.Enabled;
-                }
-            }
-
-            void SelectCurrentMenuBarItem ()
-            {
-                MenuBarItem menuBarItem = null;
-
-                if (_menuBar?.Menus is { Length: > 0 })
-                {
-                    menuBarItem = _menuBar.Menus [_currentSelectedMenuBar];
-                    lblMenuBar.Text = menuBarItem.Title;
-                }
-
-                SetFrameDetails (menuBarItem);
-                _currentMenuBarItem = menuBarItem;
-                DataContext.Menus = new ();
-                SetListViewSource (_currentMenuBarItem, true);
-                lblParent.Text = string.Empty;
-
-                if (_currentMenuBarItem is null)
-                {
-                    lblMenuBar.Text = string.Empty;
-                }
-            }
-
-            void SetListViewSource (MenuItem currentMenuBarItem, bool fill = false)
-            {
-                DataContext.Menus = [];
-                var menuBarItem = currentMenuBarItem as MenuBarItem;
-
-                if (menuBarItem != null && menuBarItem?.Children == null)
-                {
-                    return;
-                }
-
-                if (!fill)
-                {
-                    return;
-                }
-
-                if (menuBarItem != null)
-                {
-                    foreach (MenuItem child in menuBarItem?.Children)
-                    {
-                        var m = new DynamicMenuItemList { Title = child.Title, MenuItem = child };
-                        DataContext.Menus.Add (m);
-                    }
-                }
-            }
-
-            MenuItem CreateNewMenu (DynamicMenuItem item, MenuItem parent = null)
-            {
-                MenuItem newMenu;
-
-                if (item.HasSubMenu)
-                {
-                    newMenu = new MenuBarItem (item.Title, new MenuItem [] { }, parent);
-                }
-                else if (parent != null)
-                {
-                    newMenu = new (item.Title, item.Help, null, null, parent);
-                    newMenu.CheckType = item.CheckStyle;
-                    newMenu.Action = frmMenuDetails.CreateAction (newMenu, item);
-
-                    if (Key.TryParse (item.ShortcutKey, out Key key))
-                    {
-                        newMenu.ShortcutKey = key;
-                    }
-                    newMenu.AllowNullChecked = item.AllowNullChecked;
-                }
-                else if (item.IsTopLevel)
-                {
-                    newMenu = new MenuBarItem (item.Title, item.Help, null);
-                    newMenu.Action = frmMenuDetails.CreateAction (newMenu, item);
-
-                    if (Key.TryParse (item.ShortcutKey, out Key key))
-                    {
-                        newMenu.ShortcutKey = key;
-                    }
-                }
-                else
-                {
-                    newMenu = new MenuBarItem (item.Title, item.Help, null);
-
-                    ((MenuBarItem)newMenu).Children [0].Action =
-                        frmMenuDetails.CreateAction (newMenu, item);
-
-                    if (Key.TryParse (item.ShortcutKey, out Key key))
-                    {
-                        ((MenuBarItem)newMenu).Children [0].ShortcutKey = key;
-                    }
-                }
-
-                return newMenu;
-            }
-
-            void UpdateMenuItem (MenuItem currentEditMenuBarItem, DynamicMenuItem menuItem, int index)
-            {
-                currentEditMenuBarItem.Title = menuItem.Title;
-                currentEditMenuBarItem.Help = menuItem.Help;
-                currentEditMenuBarItem.CheckType = menuItem.CheckStyle;
-
-                if (currentEditMenuBarItem.Parent is MenuBarItem parent
-                    && parent.Children.Length == 1
-                    && currentEditMenuBarItem.CheckType == MenuItemCheckStyle.Radio)
-                {
-                    currentEditMenuBarItem.Checked = true;
-                }
-
-                if (menuItem.IsTopLevel && currentEditMenuBarItem is MenuBarItem)
-                {
-                    ((MenuBarItem)currentEditMenuBarItem).Children = null;
-
-                    currentEditMenuBarItem.Action =
-                        frmMenuDetails.CreateAction (currentEditMenuBarItem, menuItem);
-
-                    if (Key.TryParse (menuItem.ShortcutKey, out Key key))
-                    {
-                        currentEditMenuBarItem.ShortcutKey = key;
-                    }
-
-                    SetListViewSource (currentEditMenuBarItem, true);
-                }
-                else if (menuItem.HasSubMenu)
-                {
-                    currentEditMenuBarItem.Action = null;
-
-                    if (currentEditMenuBarItem is MenuBarItem && ((MenuBarItem)currentEditMenuBarItem).Children == null)
-                    {
-                        ((MenuBarItem)currentEditMenuBarItem).Children = new MenuItem [] { };
-                    }
-                    else if (currentEditMenuBarItem.Parent != null)
-                    {
-                        frmMenuDetails.UpdateParent (ref currentEditMenuBarItem);
-                    }
-                    else
-                    {
-                        currentEditMenuBarItem =
-                            new MenuBarItem (
-                                             currentEditMenuBarItem.Title,
-                                             new MenuItem [] { },
-                                             currentEditMenuBarItem.Parent
-                                            );
-                    }
-
-                    SetListViewSource (currentEditMenuBarItem, true);
-                }
-                else if (currentEditMenuBarItem is MenuBarItem && currentEditMenuBarItem.Parent != null)
-                {
-                    frmMenuDetails.UpdateParent (ref currentEditMenuBarItem);
-
-                    currentEditMenuBarItem = new (
-                                                   menuItem.Title,
-                                                   menuItem.Help,
-                                                   frmMenuDetails.CreateAction (currentEditMenuBarItem, menuItem),
-                                                   null,
-                                                   currentEditMenuBarItem.Parent
-                                                  );
-                }
-                else
-                {
-                    if (currentEditMenuBarItem is MenuBarItem)
-                    {
-                        ((MenuBarItem)currentEditMenuBarItem).Children = null;
-                        DataContext.Menus = new ();
-                    }
-
-                    currentEditMenuBarItem.Action =
-                        frmMenuDetails.CreateAction (currentEditMenuBarItem, menuItem);
-
-                    if (Key.TryParse (menuItem.ShortcutKey, out Key key))
-                    {
-                        currentEditMenuBarItem.ShortcutKey = key;
-                    }
-                }
-
-                if (currentEditMenuBarItem.Parent == null)
-                {
-                    DataContext.MenuBar = currentEditMenuBarItem.Title;
-                }
-                else
-                {
-                    if (DataContext.Menus.Count == 0)
-                    {
-                        DataContext.Menus.Add (
-                                               new ()
-                                               {
-                                                   Title = currentEditMenuBarItem.Title, MenuItem = currentEditMenuBarItem
-                                               }
-                                              );
-                    }
-
-                    DataContext.Menus [index] =
-                        new ()
-                        {
-                            Title = currentEditMenuBarItem.Title, MenuItem = currentEditMenuBarItem
-                        };
-                }
-
-                currentEditMenuBarItem.CheckType = menuItem.CheckStyle;
-                SetFrameDetails (currentEditMenuBarItem);
-            }
-
-            //_frmMenuDetails.Initialized += (s, e) => _frmMenuDetails.Enabled = false;
-        }
-
-        public DynamicMenuItemModel DataContext { get; set; }
-    }
-
-    public class DynamicMenuItem
-    {
-        public string Action { get; set; } = string.Empty;
-        public bool AllowNullChecked { get; set; }
-        public MenuItemCheckStyle CheckStyle { get; set; }
-        public bool HasSubMenu { get; set; }
-        public string Help { get; set; } = string.Empty;
-        public bool IsTopLevel { get; set; }
-        public string HotKey { get; set; }
-        public string ShortcutKey { get; set; }
-        public string Title { get; set; } = "_New";
-    }
-
-    public class DynamicMenuItemList
-    {
-        public MenuItem MenuItem { get; set; }
-        public string Title { get; set; }
-        public override string ToString () { return $"{Title}, {MenuItem.HotKey}, {MenuItem.ShortcutKey} "; }
-    }
-
-    public class DynamicMenuItemModel : INotifyPropertyChanged
-    {
-        private string _menuBar;
-        private ObservableCollection<DynamicMenuItemList> _menus;
-        private string _parent;
-        public DynamicMenuItemModel () { Menus = []; }
-
-        public string MenuBar
-        {
-            get => _menuBar;
-            set
-            {
-                if (value == _menuBar)
-                {
-                    return;
-                }
-
-                _menuBar = value;
-
-                PropertyChanged?.Invoke (
-                                         this,
-                                         new (GetPropertyName ())
-                                        );
-            }
-        }
-
-        public ObservableCollection<DynamicMenuItemList> Menus
-        {
-            get => _menus;
-            set
-            {
-                if (value == _menus)
-                {
-                    return;
-                }
-
-                _menus = value;
-
-                PropertyChanged?.Invoke (
-                                         this,
-                                         new (GetPropertyName ())
-                                        );
-            }
-        }
-
-        public string Parent
-        {
-            get => _parent;
-            set
-            {
-                if (value == _parent)
-                {
-                    return;
-                }
-
-                _parent = value;
-
-                PropertyChanged?.Invoke (
-                                         this,
-                                         new (GetPropertyName ())
-                                        );
-            }
-        }
-
-        public event PropertyChangedEventHandler PropertyChanged;
-        public string GetPropertyName ([CallerMemberName] string propertyName = null) { return propertyName; }
-    }
-
-    public interface IValueConverter
-    {
-        object Convert (object value, object parameter = null);
-    }
-
-    public class ListWrapperConverter<T> : IValueConverter
-    {
-        public object Convert (object value, object parameter = null) { return new ListWrapper<T> ((ObservableCollection<T>)value); }
-    }
-
-    public class UStringValueConverter : IValueConverter
-    {
-        public object Convert (object value, object parameter = null)
-        {
-            byte [] data = Encoding.ASCII.GetBytes (value.ToString () ?? string.Empty);
-
-            return StringExtensions.ToString (data);
-        }
-    }
-}

+ 6 - 6
Examples/UICatalog/Scenarios/DynamicStatusBar.cs

@@ -15,7 +15,7 @@ public class DynamicStatusBar : Scenario
     public override void Main ()
     public override void Main ()
     {
     {
         Application.Init ();
         Application.Init ();
-        Application.Run<DynamicStatusBarSample> ().Dispose ();
+        Application.Run<DynamicStatusBarSample> ();
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
@@ -79,7 +79,7 @@ public class DynamicStatusBar : Scenario
             }
             }
             catch (Exception ex)
             catch (Exception ex)
             {
             {
-                MessageBox.ErrorQuery ("Binding Error", $"Binding failed: {ex}.", "Ok");
+                MessageBox.ErrorQuery (ApplicationImpl.Instance, "Binding Error", $"Binding failed: {ex}.", "Ok");
             }
             }
         }
         }
     }
     }
@@ -140,7 +140,7 @@ public class DynamicStatusBar : Scenario
         public TextView TextAction { get; }
         public TextView TextAction { get; }
         public TextField TextShortcut { get; }
         public TextField TextShortcut { get; }
         public TextField TextTitle { get; }
         public TextField TextTitle { get; }
-        public Action CreateAction (DynamicStatusItem item) { return () => MessageBox.ErrorQuery (item.Title, item.Action, "Ok"); }
+        public Action CreateAction (DynamicStatusItem item) { return () => MessageBox.ErrorQuery (ApplicationImpl.Instance, item.Title, item.Action, "Ok"); }
 
 
         public void EditStatusItem (Shortcut statusItem)
         public void EditStatusItem (Shortcut statusItem)
         {
         {
@@ -184,7 +184,7 @@ public class DynamicStatusBar : Scenario
                               {
                               {
                                   if (string.IsNullOrEmpty (TextTitle.Text))
                                   if (string.IsNullOrEmpty (TextTitle.Text))
                                   {
                                   {
-                                      MessageBox.ErrorQuery ("Invalid title", "Must enter a valid title!.", "Ok");
+                                      MessageBox.ErrorQuery (App, "Invalid title", "Must enter a valid title!.", "Ok");
                                   }
                                   }
                                   else
                                   else
                                   {
                                   {
@@ -200,7 +200,7 @@ public class DynamicStatusBar : Scenario
                                       TextTitle.Text = string.Empty;
                                       TextTitle.Text = string.Empty;
                                       Application.RequestStop ();
                                       Application.RequestStop ();
                                   };
                                   };
-            var dialog = new Dialog { Title = "Enter the menu details.", Buttons = [btnOk, btnCancel], Height = Dim.Auto (DimAutoStyle.Content, 17, Application.Screen.Height) };
+            var dialog = new Dialog { Title = "Enter the menu details.", Buttons = [btnOk, btnCancel], Height = Dim.Auto (DimAutoStyle.Content, 17, App?.Screen.Height) };
 
 
             Width = Dim.Fill ();
             Width = Dim.Fill ();
             Height = Dim.Fill () - 2;
             Height = Dim.Fill () - 2;
@@ -382,7 +382,7 @@ public class DynamicStatusBar : Scenario
                               {
                               {
                                   if (string.IsNullOrEmpty (frmStatusBarDetails.TextTitle.Text) && _currentEditStatusItem != null)
                                   if (string.IsNullOrEmpty (frmStatusBarDetails.TextTitle.Text) && _currentEditStatusItem != null)
                                   {
                                   {
-                                      MessageBox.ErrorQuery ("Invalid title", "Must enter a valid title!.", "Ok");
+                                      MessageBox.ErrorQuery (App, "Invalid title", "Must enter a valid title!.", "Ok");
                                   }
                                   }
                                   else if (_currentEditStatusItem != null)
                                   else if (_currentEditStatusItem != null)
                                   {
                                   {

File diff suppressed because it is too large
+ 504 - 677
Examples/UICatalog/Scenarios/Editor.cs


+ 39 - 17
Examples/UICatalog/Scenarios/EditorsAndHelpers/AllViewsView.cs

@@ -4,6 +4,7 @@ namespace UICatalog.Scenarios;
 public class AllViewsView : View
 public class AllViewsView : View
 {
 {
     private const int MAX_VIEW_FRAME_HEIGHT = 25;
     private const int MAX_VIEW_FRAME_HEIGHT = 25;
+
     public AllViewsView ()
     public AllViewsView ()
     {
     {
         CanFocus = true;
         CanFocus = true;
@@ -24,6 +25,7 @@ public class AllViewsView : View
         AddCommand (Command.Down, () => ScrollVertical (1));
         AddCommand (Command.Down, () => ScrollVertical (1));
         AddCommand (Command.PageUp, () => ScrollVertical (-SubViews.OfType<FrameView> ().First ().Frame.Height));
         AddCommand (Command.PageUp, () => ScrollVertical (-SubViews.OfType<FrameView> ().First ().Frame.Height));
         AddCommand (Command.PageDown, () => ScrollVertical (SubViews.OfType<FrameView> ().First ().Frame.Height));
         AddCommand (Command.PageDown, () => ScrollVertical (SubViews.OfType<FrameView> ().First ().Frame.Height));
+
         AddCommand (
         AddCommand (
                     Command.Start,
                     Command.Start,
                     () =>
                     () =>
@@ -32,6 +34,7 @@ public class AllViewsView : View
 
 
                         return true;
                         return true;
                     });
                     });
+
         AddCommand (
         AddCommand (
                     Command.End,
                     Command.End,
                     () =>
                     () =>
@@ -65,12 +68,12 @@ public class AllViewsView : View
         MouseBindings.Add (MouseFlags.WheeledRight, Command.ScrollRight);
         MouseBindings.Add (MouseFlags.WheeledRight, Command.ScrollRight);
     }
     }
 
 
-    /// <inheritdoc />
+    /// <inheritdoc/>
     public override void EndInit ()
     public override void EndInit ()
     {
     {
         base.EndInit ();
         base.EndInit ();
 
 
-        var allClasses = GetAllViewClassesCollection ();
+        List<Type> allClasses = GetAllViewClassesCollection ();
 
 
         View? previousView = null;
         View? previousView = null;
 
 
@@ -95,19 +98,6 @@ public class AllViewsView : View
         }
         }
     }
     }
 
 
-    private static List<Type> GetAllViewClassesCollection ()
-    {
-        List<Type> types = typeof (View).Assembly.GetTypes ()
-                                        .Where (
-                                                myType => myType is { IsClass: true, IsAbstract: false, IsPublic: true }
-                                                          && myType.IsSubclassOf (typeof (View)))
-                                        .ToList ();
-
-        types.Add (typeof (View));
-
-        return types;
-    }
-
     private View? CreateView (Type type)
     private View? CreateView (Type type)
     {
     {
         // If we are to create a generic Type
         // If we are to create a generic Type
@@ -125,12 +115,32 @@ public class AllViewsView : View
                 }
                 }
                 else
                 else
                 {
                 {
-                    typeArguments.Add (typeof (object));
+                    // Check if the generic parameter has constraints
+                    Type [] constraints = arg.GetGenericParameterConstraints ();
+
+                    if (constraints.Length > 0)
+                    {
+                        // Use the first constraint type to satisfy the constraint
+                        typeArguments.Add (constraints [0]);
+                    }
+                    else
+                    {
+                        typeArguments.Add (typeof (object));
+                    }
                 }
                 }
             }
             }
 
 
             // And change what type we are instantiating from MyClass<T> to MyClass<object> or MyClass<T>
             // And change what type we are instantiating from MyClass<T> to MyClass<object> or MyClass<T>
-            type = type.MakeGenericType (typeArguments.ToArray ());
+            try
+            {
+                type = type.MakeGenericType (typeArguments.ToArray ());
+            }
+            catch (ArgumentException ex)
+            {
+                Logging.Warning ($"Cannot create generic type {type} with arguments [{string.Join (", ", typeArguments.Select (t => t.Name))}]: {ex.Message}");
+
+                return null;
+            }
         }
         }
 
 
         // Ensure the type does not contain any generic parameters
         // Ensure the type does not contain any generic parameters
@@ -164,6 +174,18 @@ public class AllViewsView : View
         return view;
         return view;
     }
     }
 
 
+    private static List<Type> GetAllViewClassesCollection ()
+    {
+        List<Type> types = typeof (View).Assembly.GetTypes ()
+                                        .Where (myType => myType is { IsClass: true, IsAbstract: false, IsPublic: true }
+                                                          && myType.IsSubclassOf (typeof (View)))
+                                        .ToList ();
+
+        types.Add (typeof (View));
+
+        return types;
+    }
+
     private void OnViewInitialized (object? sender, EventArgs e)
     private void OnViewInitialized (object? sender, EventArgs e)
     {
     {
         if (sender is not View view)
         if (sender is not View view)

+ 1 - 1
Examples/UICatalog/Scenarios/EditorsAndHelpers/ArrangementEditor.cs

@@ -45,7 +45,7 @@ public sealed class ArrangementEditor : EditorBase
             if (ViewToEdit.Arrangement.HasFlag (ViewArrangement.Overlapped))
             if (ViewToEdit.Arrangement.HasFlag (ViewArrangement.Overlapped))
             {
             {
                 ViewToEdit.ShadowStyle = ShadowStyle.Transparent;
                 ViewToEdit.ShadowStyle = ShadowStyle.Transparent;
-                ViewToEdit.SchemeName = "Toplevel";
+                ViewToEdit.SchemeName = "Runnable";
             }
             }
             else
             else
             {
             {

+ 1 - 1
Examples/UICatalog/Scenarios/EditorsAndHelpers/DimEditor.cs

@@ -157,7 +157,7 @@ public class DimEditor : EditorBase
         }
         }
         catch (Exception e)
         catch (Exception e)
         {
         {
-            MessageBox.ErrorQuery ("Exception", e.Message, "Ok");
+            MessageBox.ErrorQuery (App, "Exception", e.Message, "Ok");
         }
         }
     }
     }
 }
 }

+ 1 - 1
Examples/UICatalog/Scenarios/EditorsAndHelpers/PosEditor.cs

@@ -160,7 +160,7 @@ public class PosEditor : EditorBase
         }
         }
         catch (Exception e)
         catch (Exception e)
         {
         {
-            MessageBox.ErrorQuery ("Exception", e.Message, "Ok");
+            MessageBox.ErrorQuery (App, "Exception", e.Message, "Ok");
         }
         }
     }
     }
 }
 }

+ 6 - 6
Examples/UICatalog/Scenarios/FileDialogExamples.cs

@@ -133,7 +133,7 @@ public class FileDialogExamples : Scenario
                              }
                              }
                              catch (Exception ex)
                              catch (Exception ex)
                              {
                              {
-                                 MessageBox.ErrorQuery ("Error", ex.ToString (), "_Ok");
+                                 MessageBox.ErrorQuery (ApplicationImpl.Instance, "Error", ex.ToString (), "_Ok");
                              }
                              }
                              finally
                              finally
                              {
                              {
@@ -153,7 +153,7 @@ public class FileDialogExamples : Scenario
         {
         {
             if (File.Exists (e.Dialog.Path))
             if (File.Exists (e.Dialog.Path))
             {
             {
-                int result = MessageBox.Query ("Overwrite?", "File already exists", "_Yes", "_No");
+                int? result = MessageBox.Query (ApplicationImpl.Instance, "Overwrite?", "File already exists", "_Yes", "_No");
                 e.Cancel = result == 1;
                 e.Cancel = result == 1;
             }
             }
         }
         }
@@ -243,12 +243,12 @@ public class FileDialogExamples : Scenario
             IReadOnlyList<string> multiSelected = fd.MultiSelected;
             IReadOnlyList<string> multiSelected = fd.MultiSelected;
             string path = fd.Path;
             string path = fd.Path;
 
 
-            // This needs to be disposed before opening other toplevel
+            // This needs to be disposed before opening other runnable
             fd.Dispose ();
             fd.Dispose ();
 
 
             if (canceled)
             if (canceled)
             {
             {
-                MessageBox.Query (
+                MessageBox.Query (ApplicationImpl.Instance,
                                   "Canceled",
                                   "Canceled",
                                   "You canceled navigation and did not pick anything",
                                   "You canceled navigation and did not pick anything",
                                   "Ok"
                                   "Ok"
@@ -256,7 +256,7 @@ public class FileDialogExamples : Scenario
             }
             }
             else if (_cbAllowMultipleSelection.CheckedState == CheckState.Checked)
             else if (_cbAllowMultipleSelection.CheckedState == CheckState.Checked)
             {
             {
-                MessageBox.Query (
+                MessageBox.Query (ApplicationImpl.Instance,
                                   "Chosen!",
                                   "Chosen!",
                                   "You chose:" + Environment.NewLine + string.Join (Environment.NewLine, multiSelected.Select (m => m)),
                                   "You chose:" + Environment.NewLine + string.Join (Environment.NewLine, multiSelected.Select (m => m)),
                                   "Ok"
                                   "Ok"
@@ -264,7 +264,7 @@ public class FileDialogExamples : Scenario
             }
             }
             else
             else
             {
             {
-                MessageBox.Query (
+                MessageBox.Query (ApplicationImpl.Instance,
                                   "Chosen!",
                                   "Chosen!",
                                   "You chose:" + Environment.NewLine + path,
                                   "You chose:" + Environment.NewLine + path,
                                   "Ok"
                                   "Ok"

+ 1 - 1
Examples/UICatalog/Scenarios/Generic.cs

@@ -29,7 +29,7 @@ public sealed class Generic : Scenario
                             {
                             {
                                 // When Accepting is handled, set e.Handled to true to prevent further processing.
                                 // When Accepting is handled, set e.Handled to true to prevent further processing.
                                 e.Handled = true;
                                 e.Handled = true;
-                                MessageBox.ErrorQuery ("Error", "You pressed the button!", "_Ok");
+                                MessageBox.ErrorQuery (ApplicationImpl.Instance, "Error", "You pressed the button!", "_Ok");
                             };
                             };
 
 
         appWindow.Add (button);
         appWindow.Add (button);

+ 298 - 338
Examples/UICatalog/Scenarios/GraphViewExample.cs

@@ -1,9 +1,6 @@
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Linq;
+#nullable enable
+
 using System.Text;
 using System.Text;
-using Application = Terminal.Gui.App.Application;
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
 
 
@@ -13,144 +10,53 @@ namespace UICatalog.Scenarios;
 public class GraphViewExample : Scenario
 public class GraphViewExample : Scenario
 {
 {
     private readonly Thickness _thickness = new (1, 1, 1, 1);
     private readonly Thickness _thickness = new (1, 1, 1, 1);
-    private TextView _about;
+    private TextView? _about;
     private int _currentGraph;
     private int _currentGraph;
-    private Action [] _graphs;
-    private GraphView _graphView;
-    private MenuItem _miDiags;
-    private MenuItem _miShowBorder;
+    private Action []? _graphs;
+    private GraphView? _graphView;
+    private CheckBox? _diagCheckBox;
+    private CheckBox? _showBorderCheckBox;
     private ViewDiagnosticFlags _viewDiagnostics;
     private ViewDiagnosticFlags _viewDiagnostics;
 
 
     public override void Main ()
     public override void Main ()
     {
     {
         Application.Init ();
         Application.Init ();
-        Toplevel app = new ();
-
-        _graphs = new []
-        {
-            () => SetupPeriodicTableScatterPlot (), //0
-            () => SetupLifeExpectancyBarGraph (true), //1
-            () => SetupLifeExpectancyBarGraph (false), //2
-            () => SetupPopulationPyramid (), //3
-            () => SetupLineGraph (), //4
-            () => SetupSineWave (), //5
-            () => SetupDisco (), //6
-            () => MultiBarGraph () //7
-        };
 
 
-        var menu = new MenuBar
+        Window app = new ()
         {
         {
-            Menus =
-            [
-                new (
-                     "_File",
-                     new MenuItem []
-                     {
-                         new (
-                              "Scatter _Plot",
-                              "",
-                              () => _graphs [_currentGraph =
-                                                 0] ()
-                             ),
-                         new (
-                              "_V Bar Graph",
-                              "",
-                              () => _graphs [_currentGraph =
-                                                 1] ()
-                             ),
-                         new (
-                              "_H Bar Graph",
-                              "",
-                              () => _graphs [_currentGraph =
-                                                 2] ()
-                             ),
-                         new (
-                              "P_opulation Pyramid",
-                              "",
-                              () => _graphs [_currentGraph =
-                                                 3] ()
-                             ),
-                         new (
-                              "_Line Graph",
-                              "",
-                              () => _graphs [_currentGraph =
-                                                 4] ()
-                             ),
-                         new (
-                              "Sine _Wave",
-                              "",
-                              () => _graphs [_currentGraph =
-                                                 5] ()
-                             ),
-                         new (
-                              "Silent _Disco",
-                              "",
-                              () => _graphs [_currentGraph =
-                                                 6] ()
-                             ),
-                         new (
-                              "_Multi Bar Graph",
-                              "",
-                              () => _graphs [_currentGraph =
-                                                 7] ()
-                             ),
-                         new ("_Quit", "", () => Quit ())
-                     }
-                    ),
-                new (
-                     "_View",
-                     new []
-                     {
-                         new ("Zoom _In", "", () => Zoom (0.5f)),
-                         new ("Zoom _Out", "", () => Zoom (2f)),
-                         new ("MarginLeft++", "", () => Margin (true, true)),
-                         new ("MarginLeft--", "", () => Margin (true, false)),
-                         new ("MarginBottom++", "", () => Margin (false, true)),
-                         new ("MarginBottom--", "", () => Margin (false, false)),
-                         _miShowBorder = new (
-                                              "_Enable Margin, Border, and Padding",
-                                              "",
-                                              () => ShowBorder ()
-                                             )
-                         {
-                             Checked = true,
-                             CheckType = MenuItemCheckStyle
-                                 .Checked
-                         },
-                         _miDiags = new (
-                                         "_Diagnostics",
-                                         "",
-                                         () => ToggleDiagnostics ()
-                                        )
-                         {
-                             Checked = View.Diagnostics
-                                       == (ViewDiagnosticFlags
-                                               .Thickness
-                                           | ViewDiagnosticFlags
-                                               .Ruler),
-                             CheckType = MenuItemCheckStyle.Checked
-                         }
-                     }
-                    )
-            ]
+            BorderStyle = LineStyle.None
         };
         };
-        app.Add (menu);
 
 
+        _graphs =
+        [
+            SetupPeriodicTableScatterPlot,
+            () => SetupLifeExpectancyBarGraph (true),
+            () => SetupLifeExpectancyBarGraph (false),
+            SetupPopulationPyramid,
+            SetupLineGraph,
+            SetupSineWave,
+            SetupDisco,
+            MultiBarGraph
+        ];
+
+        // MenuBar
+        MenuBar menu = new ();
+
+        // GraphView
         _graphView = new ()
         _graphView = new ()
         {
         {
             X = 0,
             X = 0,
-            Y = 1,
+            Y = Pos.Bottom (menu),
             Width = Dim.Percent (70),
             Width = Dim.Percent (70),
             Height = Dim.Fill (1),
             Height = Dim.Fill (1),
             BorderStyle = LineStyle.Single
             BorderStyle = LineStyle.Single
         };
         };
         _graphView.Border!.Thickness = _thickness;
         _graphView.Border!.Thickness = _thickness;
         _graphView.Margin!.Thickness = _thickness;
         _graphView.Margin!.Thickness = _thickness;
-        _graphView.Padding.Thickness = _thickness;
+        _graphView.Padding!.Thickness = _thickness;
 
 
-        app.Add (_graphView);
-
-        var frameRight = new FrameView
+        // About TextView
+        FrameView frameRight = new ()
         {
         {
             X = Pos.Right (_graphView),
             X = Pos.Right (_graphView),
             Y = Pos.Top (_graphView),
             Y = Pos.Top (_graphView),
@@ -159,23 +65,24 @@ public class GraphViewExample : Scenario
             Title = "About"
             Title = "About"
         };
         };
 
 
-        frameRight.Add (
-                        _about = new () { Width = Dim.Fill (), Height = Dim.Fill (), ReadOnly = true }
-                       );
-
-        app.Add (frameRight);
-
-        var statusBar = new StatusBar (
-                                       new Shortcut []
-                                       {
-                                           new (Key.G.WithCtrl, "Next Graph", () => _graphs [_currentGraph++ % _graphs.Length] ()),
-                                           new (Key.PageUp, "Zoom In", () => Zoom (0.5f)),
-                                           new (Key.PageDown, "Zoom Out", () => Zoom (2f))
-                                       }
-                                      );
-        app.Add (statusBar);
+        _about = new ()
+        {
+            Width = Dim.Fill (),
+            Height = Dim.Fill (),
+            ReadOnly = true
+        };
+        frameRight.Add (_about);
+
+        // StatusBar
+        StatusBar statusBar = new (
+                                   [
+                                       new (Key.G.WithCtrl, "Next Graph", () => _graphs! [_currentGraph++ % _graphs.Length] ()),
+                                       new (Key.PageUp, "Zoom In", () => Zoom (0.5f)),
+                                       new (Key.PageDown, "Zoom Out", () => Zoom (2f))
+                                   ]
+                                  );
 
 
-        var diagShortcut = new Shortcut
+        Shortcut? diagShortcut = new ()
         {
         {
             Key = Key.F10,
             Key = Key.F10,
             CommandView = new CheckBox
             CommandView = new CheckBox
@@ -184,7 +91,128 @@ public class GraphViewExample : Scenario
                 CanFocus = false
                 CanFocus = false
             }
             }
         };
         };
-        statusBar.Add (diagShortcut).Accepting += DiagShortcut_Accept;
+        
+        statusBar.Add (diagShortcut);
+        diagShortcut.Accepting += DiagShortcut_Accept;
+
+        // Menu setup
+        _showBorderCheckBox = new ()
+        {
+            Title = "_Enable Margin, Border, and Padding",
+            CheckedState = CheckState.Checked
+        };
+        _showBorderCheckBox.CheckedStateChanged += (s, e) => ShowBorder ();
+
+        _diagCheckBox = new ()
+        {
+            Title = "_Diagnostics",
+            CheckedState = View.Diagnostics == (ViewDiagnosticFlags.Thickness | ViewDiagnosticFlags.Ruler)
+                               ? CheckState.Checked
+                               : CheckState.UnChecked
+        };
+        _diagCheckBox.CheckedStateChanged += (s, e) => ToggleDiagnostics ();
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "Scatter _Plot",
+                                           Action = () => _graphs [_currentGraph = 0] ()
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_V Bar Graph",
+                                           Action = () => _graphs [_currentGraph = 1] ()
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_H Bar Graph",
+                                           Action = () => _graphs [_currentGraph = 2] ()
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "P_opulation Pyramid",
+                                           Action = () => _graphs [_currentGraph = 3] ()
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Line Graph",
+                                           Action = () => _graphs [_currentGraph = 4] ()
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "Sine _Wave",
+                                           Action = () => _graphs [_currentGraph = 5] ()
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "Silent _Disco",
+                                           Action = () => _graphs [_currentGraph = 6] ()
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Multi Bar Graph",
+                                           Action = () => _graphs [_currentGraph = 7] ()
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Action = Quit
+                                       }
+                                   ]
+                                  )
+                 );
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_View",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "Zoom _In",
+                                           Action = () => Zoom (0.5f)
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "Zoom _Out",
+                                           Action = () => Zoom (2f)
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "MarginLeft++",
+                                           Action = () => Margin (true, true)
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "MarginLeft--",
+                                           Action = () => Margin (true, false)
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "MarginBottom++",
+                                           Action = () => Margin (false, true)
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "MarginBottom--",
+                                           Action = () => Margin (false, false)
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _showBorderCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _diagCheckBox
+                                       }
+                                   ]
+                                  )
+                 );
+
+        // Add views in order of visual appearance
+        app.Add (menu, _graphView, frameRight, statusBar);
 
 
         _graphs [_currentGraph++ % _graphs.Length] ();
         _graphs [_currentGraph++ % _graphs.Length] ();
 
 
@@ -195,29 +223,31 @@ public class GraphViewExample : Scenario
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
-    private void DiagShortcut_Accept (object sender, CommandEventArgs e)
+    private void DiagShortcut_Accept (object? sender, CommandEventArgs e)
     {
     {
         ToggleDiagnostics ();
         ToggleDiagnostics ();
 
 
         if (sender is Shortcut shortcut && shortcut.CommandView is CheckBox checkBox)
         if (sender is Shortcut shortcut && shortcut.CommandView is CheckBox checkBox)
         {
         {
-            checkBox.CheckedState = _miDiags.Checked ?? false ? CheckState.Checked : CheckState.UnChecked;
+            checkBox.CheckedState = _diagCheckBox?.CheckedState ?? CheckState.UnChecked;
         }
         }
     }
     }
 
 
     private void ToggleDiagnostics ()
     private void ToggleDiagnostics ()
     {
     {
-        _miDiags.Checked = !_miDiags.Checked;
-
-        View.Diagnostics = _miDiags.Checked == true
-                               ? ViewDiagnosticFlags.Thickness
-                                 | ViewDiagnosticFlags.Ruler
+        View.Diagnostics = _diagCheckBox?.CheckedState == CheckState.Checked
+                               ? ViewDiagnosticFlags.Thickness | ViewDiagnosticFlags.Ruler
                                : ViewDiagnosticFlags.Off;
                                : ViewDiagnosticFlags.Off;
         Application.LayoutAndDraw ();
         Application.LayoutAndDraw ();
     }
     }
 
 
     private void Margin (bool left, bool increase)
     private void Margin (bool left, bool increase)
     {
     {
+        if (_graphView is null)
+        {
+            return;
+        }
+
         if (left)
         if (left)
         {
         {
             _graphView.MarginLeft = (uint)Math.Max (0, _graphView.MarginLeft + (increase ? 1 : -1));
             _graphView.MarginLeft = (uint)Math.Max (0, _graphView.MarginLeft + (increase ? 1 : -1));
@@ -232,6 +262,11 @@ public class GraphViewExample : Scenario
 
 
     private void MultiBarGraph ()
     private void MultiBarGraph ()
     {
     {
+        if (_graphView is null || _about is null)
+        {
+            return;
+        }
+
         _graphView.Reset ();
         _graphView.Reset ();
 
 
         _graphView.Title = "Multi Bar";
         _graphView.Title = "Multi Bar";
@@ -241,14 +276,14 @@ public class GraphViewExample : Scenario
         Color fore = _graphView.GetAttributeForRole (VisualRole.Normal).Foreground == Color.Black
         Color fore = _graphView.GetAttributeForRole (VisualRole.Normal).Foreground == Color.Black
                          ? Color.White
                          ? Color.White
                          : _graphView.GetAttributeForRole (VisualRole.Normal).Foreground;
                          : _graphView.GetAttributeForRole (VisualRole.Normal).Foreground;
-        var black = new Attribute (fore, Color.Black);
-        var cyan = new Attribute (Color.BrightCyan, Color.Black);
-        var magenta = new Attribute (Color.BrightMagenta, Color.Black);
-        var red = new Attribute (Color.BrightRed, Color.Black);
+        Attribute black = new (fore, Color.Black);
+        Attribute cyan = new (Color.BrightCyan, Color.Black);
+        Attribute magenta = new (Color.BrightMagenta, Color.Black);
+        Attribute red = new (Color.BrightRed, Color.Black);
 
 
         _graphView.GraphColor = black;
         _graphView.GraphColor = black;
 
 
-        var series = new MultiBarSeries (3, 1, 0.25f, new [] { magenta, cyan, red });
+        MultiBarSeries series = new (3, 1, 0.25f, [magenta, cyan, red]);
 
 
         Rune stiple = Glyphs.Stipple;
         Rune stiple = Glyphs.Stipple;
 
 
@@ -277,20 +312,20 @@ public class GraphViewExample : Scenario
 
 
         _graphView.AxisY.Minimum = 0;
         _graphView.AxisY.Minimum = 0;
 
 
-        var legend = new LegendAnnotation (new (_graphView.Viewport.Width - 20, 0, 20, 5));
+        LegendAnnotation legend = new (new (_graphView.Viewport.Width - 20, 0, 20, 5));
 
 
         legend.AddEntry (
         legend.AddEntry (
-                         new (stiple, series.SubSeries.ElementAt (0).OverrideBarColor),
+                         new (stiple, series.SubSeries.ElementAt (0).OverrideBarColor ?? black),
                          "Lower Third"
                          "Lower Third"
                         );
                         );
 
 
         legend.AddEntry (
         legend.AddEntry (
-                         new (stiple, series.SubSeries.ElementAt (1).OverrideBarColor),
+                         new (stiple, series.SubSeries.ElementAt (1).OverrideBarColor ?? cyan),
                          "Middle Third"
                          "Middle Third"
                         );
                         );
 
 
         legend.AddEntry (
         legend.AddEntry (
-                         new (stiple, series.SubSeries.ElementAt (2).OverrideBarColor),
+                         new (stiple, series.SubSeries.ElementAt (2).OverrideBarColor ?? red),
                          "Upper Third"
                          "Upper Third"
                         );
                         );
         _graphView.Annotations.Add (legend);
         _graphView.Annotations.Add (legend);
@@ -300,6 +335,11 @@ public class GraphViewExample : Scenario
 
 
     private void SetupDisco ()
     private void SetupDisco ()
     {
     {
+        if (_graphView is null || _about is null)
+        {
+            return;
+        }
+
         _graphView.Reset ();
         _graphView.Reset ();
 
 
         _graphView.Title = "Graphic Equalizer";
         _graphView.Title = "Graphic Equalizer";
@@ -308,11 +348,11 @@ public class GraphViewExample : Scenario
 
 
         _graphView.GraphColor = new Attribute (Color.White, Color.Black);
         _graphView.GraphColor = new Attribute (Color.White, Color.Black);
 
 
-        var stiple = new GraphCellToRender ((Rune)'\u2593');
+        GraphCellToRender stiple = new ((Rune)'\u2593');
 
 
-        var r = new Random ();
-        var series = new DiscoBarSeries ();
-        List<BarSeriesBar> bars = new ();
+        Random r = new ();
+        DiscoBarSeries series = new ();
+        List<BarSeriesBar> bars = [];
 
 
         Func<bool> genSample = () =>
         Func<bool> genSample = () =>
                                {
                                {
@@ -323,16 +363,13 @@ public class GraphViewExample : Scenario
                                    {
                                    {
                                        bars.Add (
                                        bars.Add (
                                                  new (null, stiple, r.Next (0, 100))
                                                  new (null, stiple, r.Next (0, 100))
-                                                 {
-                                                     //ColorGetter = colorDelegate
-                                                 }
                                                 );
                                                 );
                                    }
                                    }
 
 
-                                   _graphView.SetNeedsDraw ();
+                                   _graphView?.SetNeedsDraw ();
 
 
                                    // while the equaliser is showing
                                    // while the equaliser is showing
-                                   return _graphView.Series.Contains (series);
+                                   return _graphView is { } && _graphView.Series.Contains (series);
                                };
                                };
 
 
         Application.AddTimeout (TimeSpan.FromMilliseconds (250), genSample);
         Application.AddTimeout (TimeSpan.FromMilliseconds (250), genSample);
@@ -351,120 +388,45 @@ public class GraphViewExample : Scenario
 
 
         _graphView.SetNeedsDraw ();
         _graphView.SetNeedsDraw ();
     }
     }
-    /*
-    Country,Both,Male,Female
-
-"Switzerland",83.4,81.8,85.1
-"South Korea",83.3,80.3,86.1
-"Singapore",83.2,81,85.5
-"Spain",83.2,80.7,85.7
-"Cyprus",83.1,81.1,85.1
-"Australia",83,81.3,84.8
-"Italy",83,80.9,84.9
-"Norway",83,81.2,84.7
-"Israel",82.6,80.8,84.4
-"France",82.5,79.8,85.1
-"Luxembourg",82.4,80.6,84.2
-"Sweden",82.4,80.8,84
-"Iceland",82.3,80.8,83.9
-"Canada",82.2,80.4,84.1
-"New Zealand",82,80.4,83.5
-"Malta,81.9",79.9,83.8
-"Ireland",81.8,80.2,83.5
-"Netherlands",81.8,80.4,83.1
-"Germany",81.7,78.7,84.8
-"Austria",81.6,79.4,83.8
-"Finland",81.6,79.2,84
-"Portugal",81.6,78.6,84.4
-"Belgium",81.4,79.3,83.5
-"United Kingdom",81.4,79.8,83
-"Denmark",81.3,79.6,83
-"Slovenia",81.3,78.6,84.1
-"Greece",81.1,78.6,83.6
-"Kuwait",81,79.3,83.9
-"Costa Rica",80.8,78.3,83.4*/
 
 
     private void SetupLifeExpectancyBarGraph (bool verticalBars)
     private void SetupLifeExpectancyBarGraph (bool verticalBars)
     {
     {
+        if (_graphView is null || _about is null)
+        {
+            return;
+        }
+
         _graphView.Reset ();
         _graphView.Reset ();
 
 
         _graphView.Title = $"Life Expectancy - {(verticalBars ? "Vertical" : "Horizontal")}";
         _graphView.Title = $"Life Expectancy - {(verticalBars ? "Vertical" : "Horizontal")}";
 
 
         _about.Text = "This graph shows the life expectancy at birth of a range of countries";
         _about.Text = "This graph shows the life expectancy at birth of a range of countries";
 
 
-        var softStiple = new GraphCellToRender ((Rune)'\u2591');
-        var mediumStiple = new GraphCellToRender ((Rune)'\u2592');
+        GraphCellToRender softStiple = new ((Rune)'\u2591');
+        GraphCellToRender mediumStiple = new ((Rune)'\u2592');
 
 
-        var barSeries = new BarSeries
+        BarSeries barSeries = new ()
         {
         {
-            Bars = new ()
-            {
+            Bars =
+            [
                 new ("Switzerland", softStiple, 83.4f),
                 new ("Switzerland", softStiple, 83.4f),
-                new (
-                     "South Korea",
-                     !verticalBars
-                         ? mediumStiple
-                         : softStiple,
-                     83.3f
-                    ),
+                new ("South Korea", !verticalBars ? mediumStiple : softStiple, 83.3f),
                 new ("Singapore", softStiple, 83.2f),
                 new ("Singapore", softStiple, 83.2f),
-                new (
-                     "Spain",
-                     !verticalBars
-                         ? mediumStiple
-                         : softStiple,
-                     83.2f
-                    ),
+                new ("Spain", !verticalBars ? mediumStiple : softStiple, 83.2f),
                 new ("Cyprus", softStiple, 83.1f),
                 new ("Cyprus", softStiple, 83.1f),
-                new (
-                     "Australia",
-                     !verticalBars
-                         ? mediumStiple
-                         : softStiple,
-                     83
-                    ),
+                new ("Australia", !verticalBars ? mediumStiple : softStiple, 83),
                 new ("Italy", softStiple, 83),
                 new ("Italy", softStiple, 83),
-                new (
-                     "Norway",
-                     !verticalBars
-                         ? mediumStiple
-                         : softStiple,
-                     83
-                    ),
+                new ("Norway", !verticalBars ? mediumStiple : softStiple, 83),
                 new ("Israel", softStiple, 82.6f),
                 new ("Israel", softStiple, 82.6f),
-                new (
-                     "France",
-                     !verticalBars
-                         ? mediumStiple
-                         : softStiple,
-                     82.5f
-                    ),
+                new ("France", !verticalBars ? mediumStiple : softStiple, 82.5f),
                 new ("Luxembourg", softStiple, 82.4f),
                 new ("Luxembourg", softStiple, 82.4f),
-                new (
-                     "Sweden",
-                     !verticalBars
-                         ? mediumStiple
-                         : softStiple,
-                     82.4f
-                    ),
+                new ("Sweden", !verticalBars ? mediumStiple : softStiple, 82.4f),
                 new ("Iceland", softStiple, 82.3f),
                 new ("Iceland", softStiple, 82.3f),
-                new (
-                     "Canada",
-                     !verticalBars
-                         ? mediumStiple
-                         : softStiple,
-                     82.2f
-                    ),
+                new ("Canada", !verticalBars ? mediumStiple : softStiple, 82.2f),
                 new ("New Zealand", softStiple, 82),
                 new ("New Zealand", softStiple, 82),
-                new (
-                     "Malta",
-                     !verticalBars
-                         ? mediumStiple
-                         : softStiple,
-                     81.9f
-                    ),
+                new ("Malta", !verticalBars ? mediumStiple : softStiple, 81.9f),
                 new ("Ireland", softStiple, 81.8f)
                 new ("Ireland", softStiple, 81.8f)
-            }
+            ]
         };
         };
 
 
         _graphView.Series.Add (barSeries);
         _graphView.Series.Add (barSeries);
@@ -526,50 +488,62 @@ public class GraphViewExample : Scenario
 
 
     private void SetupLineGraph ()
     private void SetupLineGraph ()
     {
     {
+        if (_graphView is null || _about is null)
+        {
+            return;
+        }
+
         _graphView.Reset ();
         _graphView.Reset ();
 
 
         _graphView.Title = "Line";
         _graphView.Title = "Line";
 
 
         _about.Text = "This graph shows random points";
         _about.Text = "This graph shows random points";
 
 
-        var black = new Attribute (_graphView.GetAttributeForRole (VisualRole.Normal).Foreground, Color.Black, _graphView.GetAttributeForRole (VisualRole.Normal).Style);
-        var cyan = new Attribute (Color.BrightCyan, Color.Black);
-        var magenta = new Attribute (Color.BrightMagenta, Color.Black);
-        var red = new Attribute (Color.BrightRed, Color.Black);
+        Attribute black = new (
+                               _graphView.GetAttributeForRole (VisualRole.Normal).Foreground,
+                               Color.Black,
+                               _graphView.GetAttributeForRole (VisualRole.Normal).Style);
+        Attribute cyan = new (Color.BrightCyan, Color.Black);
+        Attribute magenta = new (Color.BrightMagenta, Color.Black);
+        Attribute red = new (Color.BrightRed, Color.Black);
 
 
         _graphView.GraphColor = black;
         _graphView.GraphColor = black;
 
 
-        List<PointF> randomPoints = new ();
+        List<PointF> randomPoints = [];
 
 
-        var r = new Random ();
+        Random r = new ();
 
 
         for (var i = 0; i < 10; i++)
         for (var i = 0; i < 10; i++)
         {
         {
             randomPoints.Add (new (r.Next (100), r.Next (100)));
             randomPoints.Add (new (r.Next (100), r.Next (100)));
         }
         }
 
 
-        var points = new ScatterSeries { Points = randomPoints };
+        ScatterSeries points = new () { Points = randomPoints };
 
 
-        var line = new PathAnnotation
+        PathAnnotation line = new ()
         {
         {
-            LineColor = cyan, Points = randomPoints.OrderBy (p => p.X).ToList (), BeforeSeries = true
+            LineColor = cyan,
+            Points = randomPoints.OrderBy (p => p.X).ToList (),
+            BeforeSeries = true
         };
         };
 
 
         _graphView.Series.Add (points);
         _graphView.Series.Add (points);
         _graphView.Annotations.Add (line);
         _graphView.Annotations.Add (line);
 
 
-        randomPoints = new ();
+        randomPoints = [];
 
 
         for (var i = 0; i < 10; i++)
         for (var i = 0; i < 10; i++)
         {
         {
             randomPoints.Add (new (r.Next (100), r.Next (100)));
             randomPoints.Add (new (r.Next (100), r.Next (100)));
         }
         }
 
 
-        var points2 = new ScatterSeries { Points = randomPoints, Fill = new ((Rune)'x', red) };
+        ScatterSeries points2 = new () { Points = randomPoints, Fill = new ((Rune)'x', red) };
 
 
-        var line2 = new PathAnnotation
+        PathAnnotation line2 = new ()
         {
         {
-            LineColor = magenta, Points = randomPoints.OrderBy (p => p.X).ToList (), BeforeSeries = true
+            LineColor = magenta,
+            Points = randomPoints.OrderBy (p => p.X).ToList (),
+            BeforeSeries = true
         };
         };
 
 
         _graphView.Series.Add (points2);
         _graphView.Series.Add (points2);
@@ -609,6 +583,11 @@ public class GraphViewExample : Scenario
 
 
     private void SetupPeriodicTableScatterPlot ()
     private void SetupPeriodicTableScatterPlot ()
     {
     {
+        if (_graphView is null || _about is null)
+        {
+            return;
+        }
+
         _graphView.Reset ();
         _graphView.Reset ();
 
 
         _graphView.Title = "Scatter Plot";
         _graphView.Title = "Scatter Plot";
@@ -620,8 +599,8 @@ public class GraphViewExample : Scenario
         _graphView.Series.Add (
         _graphView.Series.Add (
                                new ScatterSeries
                                new ScatterSeries
                                {
                                {
-                                   Points = new ()
-                                   {
+                                   Points =
+                                   [
                                        new (1, 1.007f),
                                        new (1, 1.007f),
                                        new (2, 4.002f),
                                        new (2, 4.002f),
                                        new (3, 6.941f),
                                        new (3, 6.941f),
@@ -737,7 +716,7 @@ public class GraphViewExample : Scenario
                                        new (116, 292),
                                        new (116, 292),
                                        new (117, 295),
                                        new (117, 295),
                                        new (118, 294)
                                        new (118, 294)
-                                   }
+                                   ]
                                }
                                }
                               );
                               );
 
 
@@ -764,29 +743,10 @@ public class GraphViewExample : Scenario
 
 
     private void SetupPopulationPyramid ()
     private void SetupPopulationPyramid ()
     {
     {
-        /*
-        Age,M,F
-0-4,2009363,1915127
-5-9,2108550,2011016
-10-14,2022370,1933970
-15-19,1880611,1805522
-20-24,2072674,2001966
-25-29,2275138,2208929
-30-34,2361054,2345774
-35-39,2279836,2308360
-40-44,2148253,2159877
-45-49,2128343,2167778
-50-54,2281421,2353119
-55-59,2232388,2306537
-60-64,1919839,1985177
-65-69,1647391,1734370
-70-74,1624635,1763853
-75-79,1137438,1304709
-80-84,766956,969611
-85-89,438663,638892
-90-94,169952,320625
-95-99,34524,95559
-100+,3016,12818*/
+        if (_graphView is null || _about is null)
+        {
+            return;
+        }
 
 
         _about.Text = "This graph shows population of each age divided by gender";
         _about.Text = "This graph shows population of each age divided by gender";
 
 
@@ -816,16 +776,16 @@ public class GraphViewExample : Scenario
         _graphView.AxisY.ShowLabelsEvery = 0;
         _graphView.AxisY.ShowLabelsEvery = 0;
         _graphView.AxisY.Minimum = 0;
         _graphView.AxisY.Minimum = 0;
 
 
-        var stiple = new GraphCellToRender (Glyphs.Stipple);
+        GraphCellToRender stiple = new (Glyphs.Stipple);
 
 
         // Bars in 2 directions
         // Bars in 2 directions
 
 
         // Males (negative to make the bars go left)
         // Males (negative to make the bars go left)
-        var malesSeries = new BarSeries
+        BarSeries malesSeries = new ()
         {
         {
             Orientation = Orientation.Horizontal,
             Orientation = Orientation.Horizontal,
-            Bars = new ()
-            {
+            Bars =
+            [
                 new ("0-4", stiple, -2009363),
                 new ("0-4", stiple, -2009363),
                 new ("5-9", stiple, -2108550),
                 new ("5-9", stiple, -2108550),
                 new ("10-14", stiple, -2022370),
                 new ("10-14", stiple, -2022370),
@@ -847,16 +807,16 @@ public class GraphViewExample : Scenario
                 new ("90-94", stiple, -169952),
                 new ("90-94", stiple, -169952),
                 new ("95-99", stiple, -34524),
                 new ("95-99", stiple, -34524),
                 new ("100+", stiple, -3016)
                 new ("100+", stiple, -3016)
-            }
+            ]
         };
         };
         _graphView.Series.Add (malesSeries);
         _graphView.Series.Add (malesSeries);
 
 
         // Females
         // Females
-        var femalesSeries = new BarSeries
+        BarSeries femalesSeries = new ()
         {
         {
             Orientation = Orientation.Horizontal,
             Orientation = Orientation.Horizontal,
-            Bars = new ()
-            {
+            Bars =
+            [
                 new ("0-4", stiple, 1915127),
                 new ("0-4", stiple, 1915127),
                 new ("5-9", stiple, 2011016),
                 new ("5-9", stiple, 2011016),
                 new ("10-14", stiple, 1933970),
                 new ("10-14", stiple, 1933970),
@@ -878,11 +838,11 @@ public class GraphViewExample : Scenario
                 new ("90-94", stiple, 320625),
                 new ("90-94", stiple, 320625),
                 new ("95-99", stiple, 95559),
                 new ("95-99", stiple, 95559),
                 new ("100+", stiple, 12818)
                 new ("100+", stiple, 12818)
-            }
+            ]
         };
         };
 
 
-        var softStiple = new GraphCellToRender ((Rune)'\u2591');
-        var mediumStiple = new GraphCellToRender ((Rune)'\u2592');
+        GraphCellToRender softStiple = new ((Rune)'\u2591');
+        GraphCellToRender mediumStiple = new ((Rune)'\u2592');
 
 
         for (var i = 0; i < malesSeries.Bars.Count; i++)
         for (var i = 0; i < malesSeries.Bars.Count; i++)
         {
         {
@@ -903,14 +863,19 @@ public class GraphViewExample : Scenario
 
 
     private void SetupSineWave ()
     private void SetupSineWave ()
     {
     {
+        if (_graphView is null || _about is null)
+        {
+            return;
+        }
+
         _graphView.Reset ();
         _graphView.Reset ();
 
 
         _graphView.Title = "Sine Wave";
         _graphView.Title = "Sine Wave";
 
 
         _about.Text = "This graph shows a sine wave";
         _about.Text = "This graph shows a sine wave";
 
 
-        var points = new ScatterSeries ();
-        var line = new PathAnnotation ();
+        ScatterSeries points = new ();
+        PathAnnotation line = new ();
 
 
         // Draw line first so it does not draw over top of points or axis labels
         // Draw line first so it does not draw over top of points or axis labels
         line.BeforeSeries = true;
         line.BeforeSeries = true;
@@ -950,25 +915,33 @@ public class GraphViewExample : Scenario
 
 
     private void ShowBorder ()
     private void ShowBorder ()
     {
     {
-        _miShowBorder.Checked = !_miShowBorder.Checked;
+        if (_graphView is null)
+        {
+            return;
+        }
 
 
-        if (_miShowBorder.Checked == true)
+        if (_showBorderCheckBox?.CheckedState == CheckState.Checked)
         {
         {
             _graphView.BorderStyle = LineStyle.Single;
             _graphView.BorderStyle = LineStyle.Single;
             _graphView.Border!.Thickness = _thickness;
             _graphView.Border!.Thickness = _thickness;
             _graphView.Margin!.Thickness = _thickness;
             _graphView.Margin!.Thickness = _thickness;
-            _graphView.Padding.Thickness = _thickness;
+            _graphView.Padding!.Thickness = _thickness;
         }
         }
         else
         else
         {
         {
             _graphView.BorderStyle = LineStyle.None;
             _graphView.BorderStyle = LineStyle.None;
             _graphView.Margin!.Thickness = Thickness.Empty;
             _graphView.Margin!.Thickness = Thickness.Empty;
-            _graphView.Padding.Thickness = Thickness.Empty;
+            _graphView.Padding!.Thickness = Thickness.Empty;
         }
         }
     }
     }
 
 
     private void Zoom (float factor)
     private void Zoom (float factor)
     {
     {
+        if (_graphView is null)
+        {
+            return;
+        }
+
         _graphView.CellSize = new (
         _graphView.CellSize = new (
                                    _graphView.CellSize.X * factor,
                                    _graphView.CellSize.X * factor,
                                    _graphView.CellSize.Y * factor
                                    _graphView.CellSize.Y * factor
@@ -980,7 +953,7 @@ public class GraphViewExample : Scenario
         _graphView.SetNeedsDraw ();
         _graphView.SetNeedsDraw ();
     }
     }
 
 
-    private class DiscoBarSeries : BarSeries
+    private sealed class DiscoBarSeries : BarSeries
     {
     {
         private readonly Attribute _brightgreen;
         private readonly Attribute _brightgreen;
         private readonly Attribute _brightred;
         private readonly Attribute _brightred;
@@ -999,35 +972,22 @@ public class GraphViewExample : Scenario
 
 
         protected override void DrawBarLine (GraphView graph, Point start, Point end, BarSeriesBar beingDrawn)
         protected override void DrawBarLine (GraphView graph, Point start, Point end, BarSeriesBar beingDrawn)
         {
         {
-            IDriver driver = Application.Driver;
-
             int x = start.X;
             int x = start.X;
 
 
             for (int y = end.Y; y <= start.Y; y++)
             for (int y = end.Y; y <= start.Y; y++)
             {
             {
                 float height = graph.ScreenToGraphSpace (x, y).Y;
                 float height = graph.ScreenToGraphSpace (x, y).Y;
 
 
-                if (height >= 85)
-                {
-                    graph.SetAttribute (_red);
-                }
-                else if (height >= 66)
-                {
-                    graph.SetAttribute (_brightred);
-                }
-                else if (height >= 45)
-                {
-                    graph.SetAttribute (_brightyellow);
-                }
-                else if (height >= 25)
-                {
-                    graph.SetAttribute (_brightgreen);
-                }
-                else
-                {
-                    graph.SetAttribute (_green);
-                }
+                Attribute attr = height switch
+                                 {
+                                     >= 85 => _red,
+                                     >= 66 => _brightred,
+                                     >= 45 => _brightyellow,
+                                     >= 25 => _brightgreen,
+                                     _ => _green
+                                 };
 
 
+                graph.SetAttribute (attr);
                 graph.AddRune (x, y, beingDrawn.Fill.Rune);
                 graph.AddRune (x, y, beingDrawn.Fill.Rune);
             }
             }
         }
         }

+ 9 - 9
Examples/UICatalog/Scenarios/HexEditor.cs

@@ -14,7 +14,7 @@ public class HexEditor : Scenario
 {
 {
     private string? _fileName;
     private string? _fileName;
     private HexView? _hexView;
     private HexView? _hexView;
-    private MenuItemv2? _miReadOnly;
+    private MenuItem? _miReadOnly;
     private bool _saved = true;
     private bool _saved = true;
     private Shortcut? _scAddress;
     private Shortcut? _scAddress;
     private Shortcut? _scInfo;
     private Shortcut? _scInfo;
@@ -49,13 +49,13 @@ public class HexEditor : Scenario
 
 
         app.Add (_hexView);
         app.Add (_hexView);
 
 
-        var menu = new MenuBarv2
+        var menu = new MenuBar
         {
         {
             Menus =
             Menus =
             [
             [
                 new (
                 new (
                      "_File",
                      "_File",
-                     new MenuItemv2 []
+                     new MenuItem []
                      {
                      {
                          new ("_New", "", New),
                          new ("_New", "", New),
                          new ("_Open", "", Open),
                          new ("_Open", "", Open),
@@ -66,7 +66,7 @@ public class HexEditor : Scenario
                     ),
                     ),
                 new (
                 new (
                      "_Edit",
                      "_Edit",
-                     new MenuItemv2 []
+                     new MenuItem []
                      {
                      {
                          new ("_Copy", "", Copy),
                          new ("_Copy", "", Copy),
                          new ("C_ut", "", Cut),
                          new ("C_ut", "", Cut),
@@ -75,7 +75,7 @@ public class HexEditor : Scenario
                     ),
                     ),
                 new (
                 new (
                      "_Options",
                      "_Options",
-                     new MenuItemv2 []
+                     new MenuItem []
                      {
                      {
                          _miReadOnly = new (
                          _miReadOnly = new (
                                               "_Read Only",
                                               "_Read Only",
@@ -181,7 +181,7 @@ public class HexEditor : Scenario
         }
         }
     }
     }
 
 
-    private void Copy () { MessageBox.ErrorQuery ("Not Implemented", "Functionality not yet implemented.", "Ok"); }
+    private void Copy () { MessageBox.ErrorQuery (ApplicationImpl.Instance, "Not Implemented", "Functionality not yet implemented.", "Ok"); }
 
 
     private void CreateDemoFile (string fileName)
     private void CreateDemoFile (string fileName)
     {
     {
@@ -208,7 +208,7 @@ public class HexEditor : Scenario
         ms.Close ();
         ms.Close ();
     }
     }
 
 
-    private void Cut () { MessageBox.ErrorQuery ("Not Implemented", "Functionality not yet implemented.", "Ok"); }
+    private void Cut () { MessageBox.ErrorQuery (ApplicationImpl.Instance, "Not Implemented", "Functionality not yet implemented.", "Ok"); }
 
 
     private Stream LoadFile ()
     private Stream LoadFile ()
     {
     {
@@ -216,7 +216,7 @@ public class HexEditor : Scenario
 
 
         if (!_saved && _hexView!.Edits.Count > 0 && _hexView.Source is {})
         if (!_saved && _hexView!.Edits.Count > 0 && _hexView.Source is {})
         {
         {
-            if (MessageBox.ErrorQuery (
+            if (MessageBox.ErrorQuery (ApplicationImpl.Instance,
                                        "Save",
                                        "Save",
                                        "The changes were not saved. Want to open without saving?",
                                        "The changes were not saved. Want to open without saving?",
                                        "_Yes",
                                        "_Yes",
@@ -267,7 +267,7 @@ public class HexEditor : Scenario
         d.Dispose ();
         d.Dispose ();
     }
     }
 
 
-    private void Paste () { MessageBox.ErrorQuery ("Not Implemented", "Functionality not yet implemented.", "_Ok"); }
+    private void Paste () { MessageBox.ErrorQuery (ApplicationImpl.Instance, "Not Implemented", "Functionality not yet implemented.", "_Ok"); }
     private void Quit () { Application.RequestStop (); }
     private void Quit () { Application.RequestStop (); }
 
 
     private void Save ()
     private void Save ()

+ 3 - 3
Examples/UICatalog/Scenarios/Images.cs

@@ -183,7 +183,7 @@ public class Images : Scenario
 
 
         if (!_sixelSupportResult.SupportsTransparency)
         if (!_sixelSupportResult.SupportsTransparency)
         {
         {
-            if (MessageBox.Query (
+            if (MessageBox.Query (ApplicationImpl.Instance,
                                   "Transparency Not Supported",
                                   "Transparency Not Supported",
                                   "It looks like your terminal does not support transparent sixel backgrounds. Do you want to try anyway?",
                                   "It looks like your terminal does not support transparent sixel backgrounds. Do you want to try anyway?",
                                   "Yes",
                                   "Yes",
@@ -288,7 +288,7 @@ public class Images : Scenario
         }
         }
         catch (Exception ex)
         catch (Exception ex)
         {
         {
-            MessageBox.ErrorQuery ("Could not open file", ex.Message, "Ok");
+            MessageBox.ErrorQuery (ApplicationImpl.Instance, "Could not open file", ex.Message, "Ok");
 
 
             return;
             return;
         }
         }
@@ -492,7 +492,7 @@ public class Images : Scenario
     {
     {
         if (_imageView.FullResImage == null)
         if (_imageView.FullResImage == null)
         {
         {
-            MessageBox.Query ("No Image Loaded", "You must first open an image.  Use the 'Open Image' button above.", "Ok");
+            MessageBox.Query (ApplicationImpl.Instance, "No Image Loaded", "You must first open an image.  Use the 'Open Image' button above.", "Ok");
 
 
             return;
             return;
         }
         }

+ 71 - 43
Examples/UICatalog/Scenarios/InteractiveTree.cs

@@ -1,4 +1,4 @@
-using System.Linq;
+#nullable enable
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
 
 
@@ -7,46 +7,54 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("TreeView")]
 [ScenarioCategory ("TreeView")]
 public class InteractiveTree : Scenario
 public class InteractiveTree : Scenario
 {
 {
-    private TreeView _treeView;
+    private TreeView? _treeView;
 
 
     public override void Main ()
     public override void Main ()
     {
     {
         Application.Init ();
         Application.Init ();
-        var appWindow = new Toplevel ()
+
+        Window appWindow = new ()
         {
         {
             Title = GetName (),
             Title = GetName (),
+            BorderStyle = LineStyle.None    
         };
         };
 
 
-        var menu = new MenuBar
-        {
-            Menus =
-            [
-                new ("_File", new MenuItem [] { new ("_Quit", "", Quit) })
-            ]
-        };
-        appWindow.Add (menu);
+        // MenuBar
+        MenuBar menu = new ();
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Action = Quit
+                                       }
+                                   ]
+                                  )
+                 );
 
 
         _treeView = new ()
         _treeView = new ()
         {
         {
             X = 0,
             X = 0,
-            Y = 1,
+            Y = Pos.Bottom (menu),
             Width = Dim.Fill (),
             Width = Dim.Fill (),
             Height = Dim.Fill (1)
             Height = Dim.Fill (1)
         };
         };
         _treeView.KeyDown += TreeView_KeyPress;
         _treeView.KeyDown += TreeView_KeyPress;
 
 
-        appWindow.Add (_treeView);
+        // StatusBar
+        StatusBar statusBar = new (
+                                   [
+                                       new (Application.QuitKey, "Quit", Quit),
+                                       new (Key.C.WithCtrl, "Add Child", AddChildNode),
+                                       new (Key.T.WithCtrl, "Add Root", AddRootNode),
+                                       new (Key.R.WithCtrl, "Rename Node", RenameNode)
+                                   ]
+                                  );
 
 
-        var statusBar = new StatusBar (
-                                       new Shortcut []
-                                       {
-                                           new (Application.QuitKey, "Quit", Quit),
-                                           new (Key.C.WithCtrl, "Add Child", AddChildNode),
-                                           new (Key.T.WithCtrl, "Add Root", AddRootNode),
-                                           new (Key.R.WithCtrl, "Rename Node", RenameNode)
-                                       }
-                                      );
-        appWindow.Add (statusBar);
+        appWindow.Add (menu, _treeView, statusBar);
 
 
         Application.Run (appWindow);
         Application.Run (appWindow);
         appWindow.Dispose ();
         appWindow.Dispose ();
@@ -55,9 +63,14 @@ public class InteractiveTree : Scenario
 
 
     private void AddChildNode ()
     private void AddChildNode ()
     {
     {
-        ITreeNode node = _treeView.SelectedObject;
+        if (_treeView is null)
+        {
+            return;
+        }
 
 
-        if (node != null)
+        ITreeNode? node = _treeView.SelectedObject;
+
+        if (node is { })
         {
         {
             if (GetText ("Text", "Enter text for node:", "", out string entered))
             if (GetText ("Text", "Enter text for node:", "", out string entered))
             {
             {
@@ -69,6 +82,11 @@ public class InteractiveTree : Scenario
 
 
     private void AddRootNode ()
     private void AddRootNode ()
     {
     {
+        if (_treeView is null)
+        {
+            return;
+        }
+
         if (GetText ("Text", "Enter text for node:", "", out string entered))
         if (GetText ("Text", "Enter text for node:", "", out string entered))
         {
         {
             _treeView.AddObject (new TreeNode (entered));
             _treeView.AddObject (new TreeNode (entered));
@@ -79,20 +97,20 @@ public class InteractiveTree : Scenario
     {
     {
         var okPressed = false;
         var okPressed = false;
 
 
-        var ok = new Button { Text = "Ok", IsDefault = true };
+        Button ok = new () { Text = "Ok", IsDefault = true };
 
 
         ok.Accepting += (s, e) =>
         ok.Accepting += (s, e) =>
-                     {
-                         okPressed = true;
-                         Application.RequestStop ();
-                     };
-        var cancel = new Button { Text = "Cancel" };
+                        {
+                            okPressed = true;
+                            Application.RequestStop ();
+                        };
+        Button cancel = new () { Text = "Cancel" };
         cancel.Accepting += (s, e) => Application.RequestStop ();
         cancel.Accepting += (s, e) => Application.RequestStop ();
-        var d = new Dialog { Title = title, Buttons = [ok, cancel] };
+        Dialog d = new () { Title = title, Buttons = [ok, cancel] };
 
 
-        var lbl = new Label { X = 0, Y = 1, Text = label };
+        Label lbl = new () { X = 0, Y = 1, Text = label };
 
 
-        var tf = new TextField { Text = initialText, X = 0, Y = 2, Width = Dim.Fill () };
+        TextField tf = new () { Text = initialText, X = 0, Y = 2, Width = Dim.Fill () };
 
 
         d.Add (lbl, tf);
         d.Add (lbl, tf);
         tf.SetFocus ();
         tf.SetFocus ();
@@ -100,7 +118,7 @@ public class InteractiveTree : Scenario
         Application.Run (d);
         Application.Run (d);
         d.Dispose ();
         d.Dispose ();
 
 
-        enteredText = okPressed ? tf.Text : null;
+        enteredText = okPressed ? tf.Text : string.Empty;
 
 
         return okPressed;
         return okPressed;
     }
     }
@@ -109,9 +127,14 @@ public class InteractiveTree : Scenario
 
 
     private void RenameNode ()
     private void RenameNode ()
     {
     {
-        ITreeNode node = _treeView.SelectedObject;
+        if (_treeView is null)
+        {
+            return;
+        }
+
+        ITreeNode? node = _treeView.SelectedObject;
 
 
-        if (node != null)
+        if (node is { })
         {
         {
             if (GetText ("Text", "Enter text for node:", node.Text, out string entered))
             if (GetText ("Text", "Enter text for node:", node.Text, out string entered))
             {
             {
@@ -121,13 +144,18 @@ public class InteractiveTree : Scenario
         }
         }
     }
     }
 
 
-    private void TreeView_KeyPress (object sender, Key obj)
+    private void TreeView_KeyPress (object? sender, Key obj)
     {
     {
+        if (_treeView is null)
+        {
+            return;
+        }
+
         if (obj.KeyCode == Key.Delete)
         if (obj.KeyCode == Key.Delete)
         {
         {
-            ITreeNode toDelete = _treeView.SelectedObject;
+            ITreeNode? toDelete = _treeView.SelectedObject;
 
 
-            if (toDelete == null)
+            if (toDelete is null)
             {
             {
                 return;
                 return;
             }
             }
@@ -141,11 +169,11 @@ public class InteractiveTree : Scenario
             }
             }
             else
             else
             {
             {
-                ITreeNode parent = _treeView.GetParent (toDelete);
+                ITreeNode? parent = _treeView.GetParent (toDelete);
 
 
-                if (parent == null)
+                if (parent is null)
                 {
                 {
-                    MessageBox.ErrorQuery (
+                    MessageBox.ErrorQuery (ApplicationImpl.Instance,
                                            "Could not delete",
                                            "Could not delete",
                                            $"Parent of '{toDelete}' was unexpectedly null",
                                            $"Parent of '{toDelete}' was unexpectedly null",
                                            "Ok"
                                            "Ok"

+ 4 - 4
Examples/UICatalog/Scenarios/KeyBindings.cs

@@ -164,17 +164,17 @@ public class KeyBindingsDemo : View
 
 
         AddCommand (Command.Save, ctx =>
         AddCommand (Command.Save, ctx =>
                                  {
                                  {
-                                     MessageBox.Query ($"{ctx.Command}", $"Ctx: {ctx}", buttons: "Ok");
+                                     MessageBox.Query (ApplicationImpl.Instance, $"{ctx.Command}", $"Ctx: {ctx}", buttons: "Ok");
                                      return true;
                                      return true;
                                  });
                                  });
         AddCommand (Command.New, ctx =>
         AddCommand (Command.New, ctx =>
                                 {
                                 {
-                                    MessageBox.Query ($"{ctx.Command}", $"Ctx: {ctx}", buttons: "Ok");
+                                    MessageBox.Query (ApplicationImpl.Instance, $"{ctx.Command}", $"Ctx: {ctx}", buttons: "Ok");
                                     return true;
                                     return true;
                                 });
                                 });
         AddCommand (Command.HotKey, ctx =>
         AddCommand (Command.HotKey, ctx =>
         {
         {
-            MessageBox.Query ($"{ctx.Command}", $"Ctx: {ctx}\nCommand: {ctx.Command}", buttons: "Ok");
+            MessageBox.Query (ApplicationImpl.Instance, $"{ctx.Command}", $"Ctx: {ctx}\nCommand: {ctx.Command}", buttons: "Ok");
             SetFocus ();
             SetFocus ();
             return true;
             return true;
         });
         });
@@ -189,7 +189,7 @@ public class KeyBindingsDemo : View
                                              {
                                              {
                                                  return false;
                                                  return false;
                                              }
                                              }
-                                             MessageBox.Query ($"{keyCommandContext.Binding}", $"Key: {keyCommandContext.Binding.Key}\nCommand: {ctx.Command}", buttons: "Ok");
+                                             MessageBox.Query (ApplicationImpl.Instance, $"{keyCommandContext.Binding}", $"Key: {keyCommandContext.Binding.Key}\nCommand: {ctx.Command}", buttons: "Ok");
                                              Application.RequestStop ();
                                              Application.RequestStop ();
                                              return true;
                                              return true;
                                          });
                                          });

+ 4 - 4
Examples/UICatalog/Scenarios/Keys.cs

@@ -86,7 +86,7 @@ public class Keys : Scenario
             Height = Dim.Fill (),
             Height = Dim.Fill (),
             Source = new ListWrapper<string> (keyList)
             Source = new ListWrapper<string> (keyList)
         };
         };
-        appKeyListView.SchemeName = "TopLevel";
+        appKeyListView.SchemeName = "Runnable";
         win.Add (appKeyListView);
         win.Add (appKeyListView);
 
 
         // View key events...
         // View key events...
@@ -114,7 +114,7 @@ public class Keys : Scenario
             Height = Dim.Fill (),
             Height = Dim.Fill (),
             Source = new ListWrapper<string> (keyDownList)
             Source = new ListWrapper<string> (keyDownList)
         };
         };
-        appKeyListView.SchemeName = "TopLevel";
+        appKeyListView.SchemeName = "Runnable";
         win.Add (onKeyDownListView);
         win.Add (onKeyDownListView);
 
 
         // KeyDownNotHandled
         // KeyDownNotHandled
@@ -134,7 +134,7 @@ public class Keys : Scenario
             Height = Dim.Fill (),
             Height = Dim.Fill (),
             Source = new ListWrapper<string> (keyDownNotHandledList)
             Source = new ListWrapper<string> (keyDownNotHandledList)
         };
         };
-        appKeyListView.SchemeName = "TopLevel";
+        appKeyListView.SchemeName = "Runnable";
         win.Add (onKeyDownNotHandledListView);
         win.Add (onKeyDownNotHandledListView);
 
 
 
 
@@ -155,7 +155,7 @@ public class Keys : Scenario
             Height = Dim.Fill (),
             Height = Dim.Fill (),
             Source = new ListWrapper<string> (swallowedList)
             Source = new ListWrapper<string> (swallowedList)
         };
         };
-        appKeyListView.SchemeName = "TopLevel";
+        appKeyListView.SchemeName = "Runnable";
         win.Add (onSwallowedListView);
         win.Add (onSwallowedListView);
 
 
         Application.Driver!.InputProcessor.AnsiSequenceSwallowed += (s, e) => { swallowedList.Add (e.Replace ("\x1b", "Esc")); };
         Application.Driver!.InputProcessor.AnsiSequenceSwallowed += (s, e) => { swallowedList.Add (e.Replace ("\x1b", "Esc")); };

+ 1 - 1
Examples/UICatalog/Scenarios/LineCanvasExperiment.cs

@@ -101,7 +101,7 @@ public class LineCanvasExperiment : Scenario
         //    Width = view4.Width,
         //    Width = view4.Width,
         //    Height = 5,
         //    Height = 5,
 
 
-        //    //Scheme = Colors.Schemes ["TopLevel"],
+        //    //Scheme = Colors.Schemes ["Runnable"],
         //    SuperViewRendersLineCanvas = true,
         //    SuperViewRendersLineCanvas = true,
         //    BorderStyle = LineStyle.Double
         //    BorderStyle = LineStyle.Double
         //};
         //};

+ 1 - 1
Examples/UICatalog/Scenarios/LineDrawing.cs

@@ -284,7 +284,7 @@ public class DrawingArea : View
                     SetCurrentAttribute (c.Value.Value.Attribute ?? GetAttributeForRole (VisualRole.Normal));
                     SetCurrentAttribute (c.Value.Value.Attribute ?? GetAttributeForRole (VisualRole.Normal));
 
 
                     // TODO: #2616 - Support combining sequences that don't normalize
                     // TODO: #2616 - Support combining sequences that don't normalize
-                    AddRune (c.Key.X, c.Key.Y, c.Value.Value.Rune);
+                    AddStr (c.Key.X, c.Key.Y, c.Value.Value.Grapheme);
                 }
                 }
             }
             }
         }
         }

+ 309 - 268
Examples/UICatalog/Scenarios/ListColumns.cs

@@ -1,6 +1,6 @@
-using System;
+#nullable enable
+
 using System.Collections;
 using System.Collections;
-using System.Collections.Generic;
 using System.Data;
 using System.Data;
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
@@ -13,19 +13,19 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("Scrolling")]
 [ScenarioCategory ("Scrolling")]
 public class ListColumns : Scenario
 public class ListColumns : Scenario
 {
 {
-    private Scheme _alternatingScheme;
-    private DataTable _currentTable;
-    private TableView _listColView;
-    private MenuItem _miAlternatingColors;
-    private MenuItem _miAlwaysUseNormalColorForVerticalCellLines;
-    private MenuItem _miBottomline;
-    private MenuItem _miCellLines;
-    private MenuItem _miCursor;
-    private MenuItem _miExpandLastColumn;
-    private MenuItem _miOrientVertical;
-    private MenuItem _miScrollParallel;
-    private MenuItem _miSmoothScrolling;
-    private MenuItem _miTopline;
+    private Scheme? _alternatingScheme;
+    private DataTable? _currentTable;
+    private TableView? _listColView;
+    private CheckBox? _alternatingColorsCheckBox;
+    private CheckBox? _alwaysUseNormalColorForVerticalCellLinesCheckBox;
+    private CheckBox? _bottomlineCheckBox;
+    private CheckBox? _cellLinesCheckBox;
+    private CheckBox? _cursorCheckBox;
+    private CheckBox? _expandLastColumnCheckBox;
+    private CheckBox? _orientVerticalCheckBox;
+    private CheckBox? _scrollParallelCheckBox;
+    private CheckBox? _smoothScrollingCheckBox;
+    private CheckBox? _toplineCheckBox;
 
 
     /// <summary>
     /// <summary>
     ///     Builds a simple list in which values are the index.  This helps testing that scrolling etc is working
     ///     Builds a simple list in which values are the index.  This helps testing that scrolling etc is working
@@ -35,7 +35,7 @@ public class ListColumns : Scenario
     /// <returns></returns>
     /// <returns></returns>
     public static IList BuildSimpleList (int items)
     public static IList BuildSimpleList (int items)
     {
     {
-        List<object> list = new ();
+        List<object> list = [];
 
 
         for (var i = 0; i < items; i++)
         for (var i = 0; i < items; i++)
         {
         {
@@ -47,20 +47,22 @@ public class ListColumns : Scenario
 
 
     public override void Main ()
     public override void Main ()
     {
     {
-        // Init
         Application.Init ();
         Application.Init ();
 
 
-        // Setup - Create a top-level application window and configure it.
-        Toplevel top = new ();
         Window appWindow = new ()
         Window appWindow = new ()
         {
         {
-            Title = GetQuitKeyAndName ()
+            Title = GetQuitKeyAndName (),
+            BorderStyle = LineStyle.None
         };
         };
 
 
+        // MenuBar
+        MenuBar menuBar = new ();
+
         _listColView = new ()
         _listColView = new ()
         {
         {
+            Y = Pos.Bottom(menuBar),
             Width = Dim.Fill (),
             Width = Dim.Fill (),
-            Height = Dim.Fill (),
+            Height = Dim.Fill (1),
             Style = new ()
             Style = new ()
             {
             {
                 ShowHeaders = false,
                 ShowHeaders = false,
@@ -70,178 +72,43 @@ public class ListColumns : Scenario
                 ExpandLastColumn = false
                 ExpandLastColumn = false
             }
             }
         };
         };
-        var listColStyle = new ListColumnStyle ();
-
-        var menu = new MenuBar
-        {
-            Menus =
-            [
-                new (
-                     "_File",
-                     new MenuItem []
-                     {
-                         new (
-                              "Open_BigListExample",
-                              "",
-                              () => OpenSimpleList (true)
-                             ),
-                         new (
-                              "Open_SmListExample",
-                              "",
-                              () => OpenSimpleList (false)
-                             ),
-                         new (
-                              "_CloseExample",
-                              "",
-                              () => CloseExample ()
-                             ),
-                         new ("_Quit", "", () => Quit ())
-                     }
-                    ),
-                new (
-                     "_View",
-                     new []
-                     {
-                         _miTopline =
-                             new ("_TopLine", "", () => ToggleTopline ())
-                             {
-                                 Checked = _listColView.Style
-                                                       .ShowHorizontalHeaderOverline,
-                                 CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miBottomline = new (
-                                              "_BottomLine",
-                                              "",
-                                              () => ToggleBottomline ()
-                                             )
-                         {
-                             Checked = _listColView.Style
-                                                   .ShowHorizontalBottomline,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         _miCellLines = new (
-                                             "_CellLines",
-                                             "",
-                                             () => ToggleCellLines ()
-                                            )
-                         {
-                             Checked = _listColView.Style
-                                                   .ShowVerticalCellLines,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         _miExpandLastColumn = new (
-                                                    "_ExpandLastColumn",
-                                                    "",
-                                                    () => ToggleExpandLastColumn ()
-                                                   )
-                         {
-                             Checked = _listColView.Style.ExpandLastColumn,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         _miAlwaysUseNormalColorForVerticalCellLines =
-                             new (
-                                  "_AlwaysUseNormalColorForVerticalCellLines",
-                                  "",
-                                  () =>
-                                      ToggleAlwaysUseNormalColorForVerticalCellLines ()
-                                 )
-                             {
-                                 Checked = _listColView.Style
-                                                       .AlwaysUseNormalColorForVerticalCellLines,
-                                 CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miSmoothScrolling = new (
-                                                   "_SmoothHorizontalScrolling",
-                                                   "",
-                                                   () => ToggleSmoothScrolling ()
-                                                  )
-                         {
-                             Checked = _listColView.Style
-                                                   .SmoothHorizontalScrolling,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         _miAlternatingColors = new (
-                                                     "Alternating Colors",
-                                                     "",
-                                                     () => ToggleAlternatingColors ()
-                                                    ) { CheckType = MenuItemCheckStyle.Checked },
-                         _miCursor = new (
-                                          "Invert Selected Cell First Character",
-                                          "",
-                                          () =>
-                                              ToggleInvertSelectedCellFirstCharacter ()
-                                         )
-                         {
-                             Checked = _listColView.Style
-                                                   .InvertSelectedCellFirstCharacter,
-                             CheckType = MenuItemCheckStyle.Checked
-                         }
-                     }
-                    ),
-                new (
-                     "_List",
-                     new []
-                     {
-                         //new MenuItem ("_Hide Headers", "", HideHeaders),
-                         _miOrientVertical = new (
-                                                  "_OrientVertical",
-                                                  "",
-                                                  () => ToggleVerticalOrientation ()
-                                                 )
-                         {
-                             Checked = listColStyle.Orientation
-                                       == Orientation.Vertical,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         _miScrollParallel = new (
-                                                  "_ScrollParallel",
-                                                  "",
-                                                  () => ToggleScrollParallel ()
-                                                 )
-                         {
-                             Checked = listColStyle.ScrollParallel,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         new ("Set _Max Cell Width", "", SetListMaxWidth),
-                         new ("Set Mi_n Cell Width", "", SetListMinWidth)
-                     }
-                    )
-            ]
-        };
+        ListColumnStyle listColStyle = new ();
 
 
-        var statusBar = new StatusBar (
-                                       new Shortcut []
-                                       {
-                                           new (Key.F2, "OpenBigListEx", () => OpenSimpleList (true)),
-                                           new (Key.F3, "CloseExample", CloseExample),
-                                           new (Key.F4, "OpenSmListEx", () => OpenSimpleList (false)),
-                                           new (Application.QuitKey, "Quit", Quit)
-                                       }
-                                      );
-        appWindow.Add (_listColView);
 
 
-        var selectedCellLabel = new Label
+        // Status Bar
+        StatusBar statusBar = new (
+                                   [
+                                       new (Key.F2, "OpenBigListEx", () => OpenSimpleList (true)),
+                                       new (Key.F3, "CloseExample", CloseExample),
+                                       new (Key.F4, "OpenSmListEx", () => OpenSimpleList (false)),
+                                       new (Application.QuitKey, "Quit", Quit)
+                                   ]
+                                  );
+
+        // Selected cell label
+        Label selectedCellLabel = new ()
         {
         {
             X = 0,
             X = 0,
             Y = Pos.Bottom (_listColView),
             Y = Pos.Bottom (_listColView),
             Text = "0,0",
             Text = "0,0",
-
             Width = Dim.Fill (),
             Width = Dim.Fill (),
             TextAlignment = Alignment.End
             TextAlignment = Alignment.End
         };
         };
 
 
-        appWindow.Add (selectedCellLabel);
-
-        _listColView.SelectedCellChanged += (s, e) => { selectedCellLabel.Text = $"{_listColView.SelectedRow},{_listColView.SelectedColumn}"; };
+        _listColView.SelectedCellChanged += (s, e) =>
+                                            {
+                                                if (_listColView is { })
+                                                {
+                                                    selectedCellLabel.Text = $"{_listColView.SelectedRow},{_listColView.SelectedColumn}";
+                                                }
+                                            };
         _listColView.KeyDown += TableViewKeyPress;
         _listColView.KeyDown += TableViewKeyPress;
 
 
-        //SetupScrollBar ();
-
         _alternatingScheme = new ()
         _alternatingScheme = new ()
         {
         {
-            Disabled = appWindow.GetAttributeForRole(VisualRole.Disabled),
+            Disabled = appWindow.GetAttributeForRole (VisualRole.Disabled),
             HotFocus = appWindow.GetAttributeForRole (VisualRole.HotFocus),
             HotFocus = appWindow.GetAttributeForRole (VisualRole.HotFocus),
-            Focus = appWindow.GetAttributeForRole(VisualRole.Focus),
+            Focus = appWindow.GetAttributeForRole (VisualRole.Focus),
             Normal = new (Color.White, Color.BrightBlue)
             Normal = new (Color.White, Color.BrightBlue)
         };
         };
 
 
@@ -250,37 +117,210 @@ public class ListColumns : Scenario
 
 
         _listColView.KeyBindings.ReplaceCommands (Key.Space, Command.Accept);
         _listColView.KeyBindings.ReplaceCommands (Key.Space, Command.Accept);
 
 
-        top.Add (menu, appWindow, statusBar);
-        appWindow.Y = 1;
-        appWindow.Height = Dim.Fill(Dim.Func (_ => statusBar.Frame.Height));
+        // Setup menu checkboxes
+        _toplineCheckBox = new ()
+        {
+            Title = "_TopLine",
+            CheckedState = _listColView.Style.ShowHorizontalHeaderOverline ? CheckState.Checked : CheckState.UnChecked
+        };
+        _toplineCheckBox.CheckedStateChanged += (s, e) => ToggleTopline ();
+
+        _bottomlineCheckBox = new ()
+        {
+            Title = "_BottomLine",
+            CheckedState = _listColView.Style.ShowHorizontalBottomline ? CheckState.Checked : CheckState.UnChecked
+        };
+        _bottomlineCheckBox.CheckedStateChanged += (s, e) => ToggleBottomline ();
+
+        _cellLinesCheckBox = new ()
+        {
+            Title = "_CellLines",
+            CheckedState = _listColView.Style.ShowVerticalCellLines ? CheckState.Checked : CheckState.UnChecked
+        };
+        _cellLinesCheckBox.CheckedStateChanged += (s, e) => ToggleCellLines ();
+
+        _expandLastColumnCheckBox = new ()
+        {
+            Title = "_ExpandLastColumn",
+            CheckedState = _listColView.Style.ExpandLastColumn ? CheckState.Checked : CheckState.UnChecked
+        };
+        _expandLastColumnCheckBox.CheckedStateChanged += (s, e) => ToggleExpandLastColumn ();
+
+        _alwaysUseNormalColorForVerticalCellLinesCheckBox = new ()
+        {
+            Title = "_AlwaysUseNormalColorForVerticalCellLines",
+            CheckedState = _listColView.Style.AlwaysUseNormalColorForVerticalCellLines ? CheckState.Checked : CheckState.UnChecked
+        };
+        _alwaysUseNormalColorForVerticalCellLinesCheckBox.CheckedStateChanged += (s, e) => ToggleAlwaysUseNormalColorForVerticalCellLines ();
+
+        _smoothScrollingCheckBox = new ()
+        {
+            Title = "_SmoothHorizontalScrolling",
+            CheckedState = _listColView.Style.SmoothHorizontalScrolling ? CheckState.Checked : CheckState.UnChecked
+        };
+        _smoothScrollingCheckBox.CheckedStateChanged += (s, e) => ToggleSmoothScrolling ();
+
+        _alternatingColorsCheckBox = new ()
+        {
+            Title = "Alternating Colors"
+        };
+        _alternatingColorsCheckBox.CheckedStateChanged += (s, e) => ToggleAlternatingColors ();
 
 
-        // Run - Start the application.
-        Application.Run (top);
-        top.Dispose ();
+        _cursorCheckBox = new ()
+        {
+            Title = "Invert Selected Cell First Character",
+            CheckedState = _listColView.Style.InvertSelectedCellFirstCharacter ? CheckState.Checked : CheckState.UnChecked
+        };
+        _cursorCheckBox.CheckedStateChanged += (s, e) => ToggleInvertSelectedCellFirstCharacter ();
 
 
-        // Shutdown - Calling Application.Shutdown is required.
+        _orientVerticalCheckBox = new ()
+        {
+            Title = "_OrientVertical",
+            CheckedState = listColStyle.Orientation == Orientation.Vertical ? CheckState.Checked : CheckState.UnChecked
+        };
+        _orientVerticalCheckBox.CheckedStateChanged += (s, e) => ToggleVerticalOrientation ();
+
+        _scrollParallelCheckBox = new ()
+        {
+            Title = "_ScrollParallel",
+            CheckedState = listColStyle.ScrollParallel ? CheckState.Checked : CheckState.UnChecked
+        };
+        _scrollParallelCheckBox.CheckedStateChanged += (s, e) => ToggleScrollParallel ();
+
+        menuBar.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "Open_BigListExample",
+                                           Action = () => OpenSimpleList (true)
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "Open_SmListExample",
+                                           Action = () => OpenSimpleList (false)
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_CloseExample",
+                                           Action = CloseExample
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Action = Quit
+                                       }
+                                   ]
+                                  )
+                 );
+
+        menuBar.Add (
+                  new MenuBarItem (
+                                   "_View",
+                                   [
+                                       new MenuItem
+                                       {
+                                           CommandView = _toplineCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _bottomlineCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _cellLinesCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _expandLastColumnCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _alwaysUseNormalColorForVerticalCellLinesCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _smoothScrollingCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _alternatingColorsCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _cursorCheckBox
+                                       }
+                                   ]
+                                  )
+                 );
+
+        menuBar.Add (
+                  new MenuBarItem (
+                                   "_List",
+                                   [
+                                       new MenuItem
+                                       {
+                                           CommandView = _orientVerticalCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _scrollParallelCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "Set _Max Cell Width",
+                                           Action = SetListMaxWidth
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "Set Mi_n Cell Width",
+                                           Action = SetListMinWidth
+                                       }
+                                   ]
+                                  )
+                 );
+
+        // Add views in order of visual appearance
+        appWindow.Add (menuBar, _listColView, selectedCellLabel, statusBar);
+
+        Application.Run (appWindow);
+        appWindow.Dispose ();
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
-    private void CloseExample () { _listColView.Table = null; }
+    private void CloseExample ()
+    {
+        if (_listColView is { })
+        {
+            _listColView.Table = null;
+        }
+    }
+
     private void OpenSimpleList (bool big) { SetTable (BuildSimpleList (big ? 1023 : 31)); }
     private void OpenSimpleList (bool big) { SetTable (BuildSimpleList (big ? 1023 : 31)); }
+
     private void Quit () { Application.RequestStop (); }
     private void Quit () { Application.RequestStop (); }
 
 
     private void RunListWidthDialog (string prompt, Action<TableView, int> setter, Func<TableView, int> getter)
     private void RunListWidthDialog (string prompt, Action<TableView, int> setter, Func<TableView, int> getter)
     {
     {
+        if (_listColView is null)
+        {
+            return;
+        }
+
         var accepted = false;
         var accepted = false;
-        var ok = new Button { Text = "Ok", IsDefault = true };
+        Button ok = new () { Text = "Ok", IsDefault = true };
 
 
         ok.Accepting += (s, e) =>
         ok.Accepting += (s, e) =>
-                     {
-                         accepted = true;
-                         Application.RequestStop ();
-                     };
-        var cancel = new Button { Text = "Cancel" };
+                        {
+                            accepted = true;
+                            Application.RequestStop ();
+                        };
+        Button cancel = new () { Text = "Cancel" };
         cancel.Accepting += (s, e) => { Application.RequestStop (); };
         cancel.Accepting += (s, e) => { Application.RequestStop (); };
-        var d = new Dialog { Title = prompt, Buttons = [ok, cancel] };
+        Dialog d = new () { Title = prompt, Buttons = [ok, cancel] };
 
 
-        var tf = new TextField { Text = getter (_listColView).ToString (), X = 0, Y = 0, Width = Dim.Fill () };
+        TextField tf = new () { Text = getter (_listColView).ToString (), X = 0, Y = 0, Width = Dim.Fill () };
 
 
         d.Add (tf);
         d.Add (tf);
         tf.SetFocus ();
         tf.SetFocus ();
@@ -296,7 +336,7 @@ public class ListColumns : Scenario
             }
             }
             catch (Exception ex)
             catch (Exception ex)
             {
             {
-                MessageBox.ErrorQuery (60, 20, "Failed to set", ex.Message, "Ok");
+                MessageBox.ErrorQuery (ApplicationImpl.Instance, 60, 20, "Failed to set", ex.Message, "Ok");
             }
             }
         }
         }
     }
     }
@@ -304,63 +344,37 @@ public class ListColumns : Scenario
     private void SetListMaxWidth ()
     private void SetListMaxWidth ()
     {
     {
         RunListWidthDialog ("MaxCellWidth", (s, v) => s.MaxCellWidth = v, s => s.MaxCellWidth);
         RunListWidthDialog ("MaxCellWidth", (s, v) => s.MaxCellWidth = v, s => s.MaxCellWidth);
-        _listColView.SetNeedsDraw ();
+        _listColView?.SetNeedsDraw ();
     }
     }
 
 
     private void SetListMinWidth ()
     private void SetListMinWidth ()
     {
     {
         RunListWidthDialog ("MinCellWidth", (s, v) => s.MinCellWidth = v, s => s.MinCellWidth);
         RunListWidthDialog ("MinCellWidth", (s, v) => s.MinCellWidth = v, s => s.MinCellWidth);
-        _listColView.SetNeedsDraw ();
+        _listColView?.SetNeedsDraw ();
     }
     }
 
 
     private void SetTable (IList list)
     private void SetTable (IList list)
     {
     {
+        if (_listColView is null)
+        {
+            return;
+        }
+
         _listColView.Table = new ListTableSource (list, _listColView);
         _listColView.Table = new ListTableSource (list, _listColView);
 
 
-        if ((ListTableSource)_listColView.Table != null)
+        if (_listColView.Table is ListTableSource listTableSource)
         {
         {
-            _currentTable = ((ListTableSource)_listColView.Table).DataTable;
+            _currentTable = listTableSource.DataTable;
         }
         }
     }
     }
 
 
-    //private void SetupScrollBar ()
-    //{
-    //    var scrollBar = new ScrollBarView (_listColView, true); // (listColView, true, true);
-
-    //    scrollBar.ChangedPosition += (s, e) =>
-    //                                 {
-    //                                     _listColView.RowOffset = scrollBar.Position;
-
-    //                                     if (_listColView.RowOffset != scrollBar.Position)
-    //                                     {
-    //                                         scrollBar.Position = _listColView.RowOffset;
-    //                                     }
-
-    //                                     _listColView.SetNeedsDraw ();
-    //                                 };
-    //    /*
-    //    scrollBar.OtherScrollBarView.ChangedPosition += (s,e) => {
-    //        listColView.ColumnOffset = scrollBar.OtherScrollBarView.Position;
-    //        if (listColView.ColumnOffset != scrollBar.OtherScrollBarView.Position) {
-    //            scrollBar.OtherScrollBarView.Position = listColView.ColumnOffset;
-    //        }
-    //        listColView.SetNeedsDraw ();
-    //    };
-    //    */
-
-    //    _listColView.DrawingContent += (s, e) =>
-    //                                {
-    //                                    scrollBar.Size = _listColView.Table?.Rows ?? 0;
-    //                                    scrollBar.Position = _listColView.RowOffset;
-
-    //                                    //scrollBar.OtherScrollBarView.Size = listColView.Table?.Columns - 1 ?? 0;
-    //                                    //scrollBar.OtherScrollBarView.Position = listColView.ColumnOffset;
-    //                                    scrollBar.Refresh ();
-    //                                };
-    //}
-
-    private void TableViewKeyPress (object sender, Key e)
+    private void TableViewKeyPress (object? sender, Key e)
     {
     {
+        if (_currentTable is null || _listColView is null)
+        {
+            return;
+        }
+
         if (e.KeyCode == Key.Delete)
         if (e.KeyCode == Key.Delete)
         {
         {
             // set all selected cells to null
             // set all selected cells to null
@@ -376,12 +390,14 @@ public class ListColumns : Scenario
 
 
     private void ToggleAlternatingColors ()
     private void ToggleAlternatingColors ()
     {
     {
-        //toggle menu item
-        _miAlternatingColors.Checked = !_miAlternatingColors.Checked;
+        if (_listColView is null || _alternatingColorsCheckBox is null)
+        {
+            return;
+        }
 
 
-        if (_miAlternatingColors.Checked == true)
+        if (_alternatingColorsCheckBox.CheckedState == CheckState.Checked)
         {
         {
-            _listColView.Style.RowColorGetter = a => { return a.RowIndex % 2 == 0 ? _alternatingScheme : null; };
+            _listColView.Style.RowColorGetter = a => a.RowIndex % 2 == 0 ? _alternatingScheme : null;
         }
         }
         else
         else
         {
         {
@@ -393,81 +409,106 @@ public class ListColumns : Scenario
 
 
     private void ToggleAlwaysUseNormalColorForVerticalCellLines ()
     private void ToggleAlwaysUseNormalColorForVerticalCellLines ()
     {
     {
-        _miAlwaysUseNormalColorForVerticalCellLines.Checked =
-            !_miAlwaysUseNormalColorForVerticalCellLines.Checked;
+        if (_listColView is null || _alwaysUseNormalColorForVerticalCellLinesCheckBox is null)
+        {
+            return;
+        }
 
 
         _listColView.Style.AlwaysUseNormalColorForVerticalCellLines =
         _listColView.Style.AlwaysUseNormalColorForVerticalCellLines =
-            (bool)_miAlwaysUseNormalColorForVerticalCellLines.Checked;
+            _alwaysUseNormalColorForVerticalCellLinesCheckBox.CheckedState == CheckState.Checked;
 
 
         _listColView.Update ();
         _listColView.Update ();
     }
     }
 
 
     private void ToggleBottomline ()
     private void ToggleBottomline ()
     {
     {
-        _miBottomline.Checked = !_miBottomline.Checked;
-        _listColView.Style.ShowHorizontalBottomline = (bool)_miBottomline.Checked;
+        if (_listColView is null || _bottomlineCheckBox is null)
+        {
+            return;
+        }
+
+        _listColView.Style.ShowHorizontalBottomline = _bottomlineCheckBox.CheckedState == CheckState.Checked;
         _listColView.Update ();
         _listColView.Update ();
     }
     }
 
 
     private void ToggleCellLines ()
     private void ToggleCellLines ()
     {
     {
-        _miCellLines.Checked = !_miCellLines.Checked;
-        _listColView.Style.ShowVerticalCellLines = (bool)_miCellLines.Checked;
+        if (_listColView is null || _cellLinesCheckBox is null)
+        {
+            return;
+        }
+
+        _listColView.Style.ShowVerticalCellLines = _cellLinesCheckBox.CheckedState == CheckState.Checked;
         _listColView.Update ();
         _listColView.Update ();
     }
     }
 
 
     private void ToggleExpandLastColumn ()
     private void ToggleExpandLastColumn ()
     {
     {
-        _miExpandLastColumn.Checked = !_miExpandLastColumn.Checked;
-        _listColView.Style.ExpandLastColumn = (bool)_miExpandLastColumn.Checked;
+        if (_listColView is null || _expandLastColumnCheckBox is null)
+        {
+            return;
+        }
+
+        _listColView.Style.ExpandLastColumn = _expandLastColumnCheckBox.CheckedState == CheckState.Checked;
 
 
         _listColView.Update ();
         _listColView.Update ();
     }
     }
 
 
     private void ToggleInvertSelectedCellFirstCharacter ()
     private void ToggleInvertSelectedCellFirstCharacter ()
     {
     {
-        //toggle menu item
-        _miCursor.Checked = !_miCursor.Checked;
-        _listColView.Style.InvertSelectedCellFirstCharacter = (bool)_miCursor.Checked;
+        if (_listColView is null || _cursorCheckBox is null)
+        {
+            return;
+        }
+
+        _listColView.Style.InvertSelectedCellFirstCharacter = _cursorCheckBox.CheckedState == CheckState.Checked;
         _listColView.SetNeedsDraw ();
         _listColView.SetNeedsDraw ();
     }
     }
 
 
     private void ToggleScrollParallel ()
     private void ToggleScrollParallel ()
     {
     {
-        _miScrollParallel.Checked = !_miScrollParallel.Checked;
-
-        if ((ListTableSource)_listColView.Table != null)
+        if (_listColView?.Table is not ListTableSource listTableSource || _scrollParallelCheckBox is null)
         {
         {
-            ((ListTableSource)_listColView.Table).Style.ScrollParallel = (bool)_miScrollParallel.Checked;
-            _listColView.SetNeedsDraw ();
+            return;
         }
         }
+
+        listTableSource.Style.ScrollParallel = _scrollParallelCheckBox.CheckedState == CheckState.Checked;
+        _listColView.SetNeedsDraw ();
     }
     }
 
 
     private void ToggleSmoothScrolling ()
     private void ToggleSmoothScrolling ()
     {
     {
-        _miSmoothScrolling.Checked = !_miSmoothScrolling.Checked;
-        _listColView.Style.SmoothHorizontalScrolling = (bool)_miSmoothScrolling.Checked;
+        if (_listColView is null || _smoothScrollingCheckBox is null)
+        {
+            return;
+        }
+
+        _listColView.Style.SmoothHorizontalScrolling = _smoothScrollingCheckBox.CheckedState == CheckState.Checked;
 
 
         _listColView.Update ();
         _listColView.Update ();
     }
     }
 
 
     private void ToggleTopline ()
     private void ToggleTopline ()
     {
     {
-        _miTopline.Checked = !_miTopline.Checked;
-        _listColView.Style.ShowHorizontalHeaderOverline = (bool)_miTopline.Checked;
+        if (_listColView is null || _toplineCheckBox is null)
+        {
+            return;
+        }
+
+        _listColView.Style.ShowHorizontalHeaderOverline = _toplineCheckBox.CheckedState == CheckState.Checked;
         _listColView.Update ();
         _listColView.Update ();
     }
     }
 
 
     private void ToggleVerticalOrientation ()
     private void ToggleVerticalOrientation ()
     {
     {
-        _miOrientVertical.Checked = !_miOrientVertical.Checked;
-
-        if ((ListTableSource)_listColView.Table != null)
+        if (_listColView?.Table is not ListTableSource listTableSource || _orientVerticalCheckBox is null)
         {
         {
-            ((ListTableSource)_listColView.Table).Style.Orientation = (bool)_miOrientVertical.Checked
-                                                                          ? Orientation.Vertical
-                                                                          : Orientation.Horizontal;
-            _listColView.SetNeedsDraw ();
+            return;
         }
         }
+
+        listTableSource.Style.Orientation = _orientVerticalCheckBox.CheckedState == CheckState.Checked
+                                                ? Orientation.Vertical
+                                                : Orientation.Horizontal;
+        _listColView.SetNeedsDraw ();
     }
     }
 }
 }

+ 1 - 1
Examples/UICatalog/Scenarios/ListViewWithSelection.cs

@@ -98,7 +98,7 @@ public class ListViewWithSelection : Scenario
             Height = Dim.Fill (),
             Height = Dim.Fill (),
             Source = new ListWrapper<string> (_eventList)
             Source = new ListWrapper<string> (_eventList)
         };
         };
-        _eventListView.SchemeName = "TopLevel";
+        _eventListView.SchemeName = "Runnable";
         _appWindow.Add (_eventListView);
         _appWindow.Add (_eventListView);
 
 
         _listView.SelectedItemChanged += (s, a) => LogEvent (s as View, a, "SelectedItemChanged");
         _listView.SelectedItemChanged += (s, a) => LogEvent (s as View, a, "SelectedItemChanged");

+ 2 - 2
Examples/UICatalog/Scenarios/ListsAndCombos.cs

@@ -35,7 +35,7 @@ public class ListsAndCombos : Scenario
         // ListView
         // ListView
         var lbListView = new Label
         var lbListView = new Label
         {
         {
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             X = 0,
             X = 0,
 
 
             Width = Dim.Percent (40),
             Width = Dim.Percent (40),
@@ -91,7 +91,7 @@ public class ListsAndCombos : Scenario
         // ComboBox
         // ComboBox
         var lbComboBox = new Label
         var lbComboBox = new Label
         {
         {
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             X = Pos.Right (lbListView) + 1,
             X = Pos.Right (lbListView) + 1,
 
 
             Width = Dim.Percent (40),
             Width = Dim.Percent (40),

+ 92 - 77
Examples/UICatalog/Scenarios/Localization.cs

@@ -1,7 +1,6 @@
-using System;
+#nullable enable
+
 using System.Globalization;
 using System.Globalization;
-using System.Linq;
-using System.Threading;
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
 
 
@@ -10,11 +9,11 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("Tests")]
 [ScenarioCategory ("Tests")]
 public class Localization : Scenario
 public class Localization : Scenario
 {
 {
-    private CheckBox _allowAnyCheckBox;
-    private string [] _cultureInfoNameSource;
-    private CultureInfo [] _cultureInfoSource;
+    private CheckBox? _allowAnyCheckBox;
+    private string []? _cultureInfoNameSource;
+    private CultureInfo []? _cultureInfoSource;
     private OpenMode _currentOpenMode = OpenMode.File;
     private OpenMode _currentOpenMode = OpenMode.File;
-    private ComboBox _languageComboBox;
+    private ComboBox? _languageComboBox;
     public CultureInfo CurrentCulture { get; private set; } = Thread.CurrentThread.CurrentUICulture;
     public CultureInfo CurrentCulture { get; private set; } = Thread.CurrentThread.CurrentUICulture;
 
 
     public void Quit ()
     public void Quit ()
@@ -25,6 +24,11 @@ public class Localization : Scenario
 
 
     public void SetCulture (CultureInfo culture)
     public void SetCulture (CultureInfo culture)
     {
     {
+        if (_languageComboBox is null || _cultureInfoSource is null)
+        {
+            return;
+        }
+
         if (_cultureInfoSource [_languageComboBox.SelectedItem] != culture)
         if (_cultureInfoSource [_languageComboBox.SelectedItem] != culture)
         {
         {
             _languageComboBox.SelectedItem = Array.IndexOf (_cultureInfoSource, culture);
             _languageComboBox.SelectedItem = Array.IndexOf (_cultureInfoSource, culture);
@@ -43,70 +47,67 @@ public class Localization : Scenario
     public override void Main ()
     public override void Main ()
     {
     {
         Application.Init ();
         Application.Init ();
-        var top = new Toplevel ();
-        var win = new Window { Title = GetQuitKeyAndName () };
-        _cultureInfoSource = Application.SupportedCultures.Append (CultureInfo.InvariantCulture).ToArray ();
 
 
-        _cultureInfoNameSource = Application.SupportedCultures.Select (c => $"{c.NativeName} ({c.Name})")
+        Window win = new ()
+        {
+            Title = GetQuitKeyAndName (),
+            BorderStyle = LineStyle.None
+        };
+
+        _cultureInfoSource = Application.SupportedCultures!.Append (CultureInfo.InvariantCulture).ToArray ();
+
+        _cultureInfoNameSource = Application.SupportedCultures!.Select (c => $"{c.NativeName} ({c.Name})")
                                             .Append ("Invariant")
                                             .Append ("Invariant")
                                             .ToArray ();
                                             .ToArray ();
 
 
-        MenuItem [] languageMenus = Application.SupportedCultures
-                                               .Select (
-                                                        c => new MenuItem (
-                                                                           $"{c.NativeName} ({c.Name})",
-                                                                           "",
-                                                                           () => SetCulture (c)
-                                                                          )
-                                                       )
-                                               .Concat (
-                                                        new MenuItem []
+        MenuItem [] languageMenus = Application.SupportedCultures!
+                                               .Select (c => new MenuItem
                                                         {
                                                         {
-                                                            null,
-                                                            new (
-                                                                 "Invariant",
-                                                                 "",
-                                                                 () =>
-                                                                     SetCulture (
-                                                                                 CultureInfo
-                                                                                     .InvariantCulture
-                                                                                )
-                                                                )
+                                                            Title = $"{c.NativeName} ({c.Name})",
+                                                            Action = () => SetCulture (c)
                                                         }
                                                         }
                                                        )
                                                        )
+                                               .Concat (
+                                                        [
+                                                            new ()
+                                                            {
+                                                                Title = "Invariant",
+                                                                Action = () => SetCulture (CultureInfo.InvariantCulture)
+                                                            }
+                                                        ]
+                                                       )
                                                .ToArray ();
                                                .ToArray ();
 
 
-        var menu = new MenuBar
-        {
-            Menus =
-            [
-                new (
-                     "_File",
-                     new MenuItem []
-                     {
-                         new MenuBarItem (
-                                          "_Language",
-                                          languageMenus
-                                         ),
-                         null,
-                         new ("_Quit", "", Quit)
-                     }
-                    )
-            ]
-        };
-        top.Add (menu);
-
-        var selectLanguageLabel = new Label
+        // MenuBar
+        MenuBar menu = new ();
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuBarItem (
+                                                        "_Language",
+                                                        languageMenus
+                                                       ),
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Action = Quit
+                                       }
+                                   ]
+                                  )
+                 );
+
+        Label selectLanguageLabel = new ()
         {
         {
             X = 2,
             X = 2,
-            Y = 1,
-
+            Y = Pos.Bottom (menu) + 1,
             Width = Dim.Fill (2),
             Width = Dim.Fill (2),
             Text = "Please select a language."
             Text = "Please select a language."
         };
         };
         win.Add (selectLanguageLabel);
         win.Add (selectLanguageLabel);
 
 
-        _languageComboBox = new()
+        _languageComboBox = new ()
         {
         {
             X = 2,
             X = 2,
             Y = Pos.Bottom (selectLanguageLabel) + 1,
             Y = Pos.Bottom (selectLanguageLabel) + 1,
@@ -120,11 +121,10 @@ public class Localization : Scenario
         _languageComboBox.SelectedItemChanged += LanguageComboBox_SelectChanged;
         _languageComboBox.SelectedItemChanged += LanguageComboBox_SelectChanged;
         win.Add (_languageComboBox);
         win.Add (_languageComboBox);
 
 
-        var textAndFileDialogLabel = new Label
+        Label textAndFileDialogLabel = new ()
         {
         {
             X = 2,
             X = 2,
             Y = Pos.Top (_languageComboBox) + 3,
             Y = Pos.Top (_languageComboBox) + 3,
-
             Width = Dim.Fill (2),
             Width = Dim.Fill (2),
             Height = 1,
             Height = 1,
             Text =
             Text =
@@ -132,13 +132,16 @@ public class Localization : Scenario
         };
         };
         win.Add (textAndFileDialogLabel);
         win.Add (textAndFileDialogLabel);
 
 
-        var textField = new TextView
+        TextView textField = new ()
         {
         {
-            X = 2, Y = Pos.Bottom (textAndFileDialogLabel) + 1, Width = Dim.Fill (32), Height = 1
+            X = 2,
+            Y = Pos.Bottom (textAndFileDialogLabel) + 1,
+            Width = Dim.Fill (32),
+            Height = 1
         };
         };
         win.Add (textField);
         win.Add (textField);
 
 
-        _allowAnyCheckBox = new()
+        _allowAnyCheckBox = new ()
         {
         {
             X = Pos.Right (textField) + 1,
             X = Pos.Right (textField) + 1,
             Y = Pos.Bottom (textAndFileDialogLabel) + 1,
             Y = Pos.Bottom (textAndFileDialogLabel) + 1,
@@ -147,46 +150,53 @@ public class Localization : Scenario
         };
         };
         win.Add (_allowAnyCheckBox);
         win.Add (_allowAnyCheckBox);
 
 
-        var openDialogButton = new Button
+        Button openDialogButton = new ()
         {
         {
-            X = Pos.Right (_allowAnyCheckBox) + 1, Y = Pos.Bottom (textAndFileDialogLabel) + 1, Text = "Open"
+            X = Pos.Right (_allowAnyCheckBox) + 1,
+            Y = Pos.Bottom (textAndFileDialogLabel) + 1,
+            Text = "Open"
         };
         };
         openDialogButton.Accepting += (sender, e) => ShowFileDialog (false);
         openDialogButton.Accepting += (sender, e) => ShowFileDialog (false);
         win.Add (openDialogButton);
         win.Add (openDialogButton);
 
 
-        var saveDialogButton = new Button
+        Button saveDialogButton = new ()
         {
         {
-            X = Pos.Right (openDialogButton) + 1, Y = Pos.Bottom (textAndFileDialogLabel) + 1, Text = "Save"
+            X = Pos.Right (openDialogButton) + 1,
+            Y = Pos.Bottom (textAndFileDialogLabel) + 1,
+            Text = "Save"
         };
         };
         saveDialogButton.Accepting += (sender, e) => ShowFileDialog (true);
         saveDialogButton.Accepting += (sender, e) => ShowFileDialog (true);
         win.Add (saveDialogButton);
         win.Add (saveDialogButton);
 
 
-        var wizardLabel = new Label
+        Label wizardLabel = new ()
         {
         {
             X = 2,
             X = 2,
             Y = Pos.Bottom (textField) + 1,
             Y = Pos.Bottom (textField) + 1,
-
             Width = Dim.Fill (2),
             Width = Dim.Fill (2),
             Text = "Click the button to open a wizard."
             Text = "Click the button to open a wizard."
         };
         };
         win.Add (wizardLabel);
         win.Add (wizardLabel);
 
 
-        var wizardButton = new Button { X = 2, Y = Pos.Bottom (wizardLabel) + 1, Text = "Open _wizard" };
+        Button wizardButton = new () { X = 2, Y = Pos.Bottom (wizardLabel) + 1, Text = "Open _wizard" };
         wizardButton.Accepting += (sender, e) => ShowWizard ();
         wizardButton.Accepting += (sender, e) => ShowWizard ();
         win.Add (wizardButton);
         win.Add (wizardButton);
 
 
-        win.Unloaded += (sender, e) => Quit ();
+        win.IsRunningChanged += (sender, e) => Quit ();
 
 
-        win.Y = Pos.Bottom (menu);
-        top.Add (win);
+        win.Add (menu);
 
 
-        Application.Run (top);
-        top.Dispose ();
+        Application.Run (win);
+        win.Dispose ();
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
     public void ShowFileDialog (bool isSaveFile)
     public void ShowFileDialog (bool isSaveFile)
     {
     {
+        if (_allowAnyCheckBox is null)
+        {
+            return;
+        }
+
         FileDialog dialog = isSaveFile ? new SaveDialog () : new OpenDialog { OpenMode = _currentOpenMode };
         FileDialog dialog = isSaveFile ? new SaveDialog () : new OpenDialog { OpenMode = _currentOpenMode };
 
 
         dialog.AllowedTypes =
         dialog.AllowedTypes =
@@ -213,16 +223,21 @@ public class Localization : Scenario
 
 
     public void ShowWizard ()
     public void ShowWizard ()
     {
     {
-        var wizard = new Wizard { Height = 8, Width = 36, Title = "The wizard" };
-        wizard.AddStep (new() { HelpText = "Wizard first step" });
-        wizard.AddStep (new() { HelpText = "Wizard step 2", NextButtonText = ">>> (_N)" });
-        wizard.AddStep (new() { HelpText = "Wizard last step" });
+        Wizard wizard = new () { Height = 8, Width = 36, Title = "The wizard" };
+        wizard.AddStep (new () { HelpText = "Wizard first step" });
+        wizard.AddStep (new () { HelpText = "Wizard step 2", NextButtonText = ">>> (_N)" });
+        wizard.AddStep (new () { HelpText = "Wizard last step" });
         Application.Run (wizard);
         Application.Run (wizard);
         wizard.Dispose ();
         wizard.Dispose ();
     }
     }
 
 
-    private void LanguageComboBox_SelectChanged (object sender, ListViewItemEventArgs e)
+    private void LanguageComboBox_SelectChanged (object? sender, ListViewItemEventArgs e)
     {
     {
+        if (_cultureInfoNameSource is null || _cultureInfoSource is null)
+        {
+            return;
+        }
+
         if (e.Value is string cultureName)
         if (e.Value is string cultureName)
         {
         {
             int index = Array.IndexOf (_cultureInfoNameSource, cultureName);
             int index = Array.IndexOf (_cultureInfoNameSource, cultureName);

+ 7 - 7
Examples/UICatalog/Scenarios/Mazing.cs

@@ -9,7 +9,7 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("Games")]
 [ScenarioCategory ("Games")]
 public class Mazing : Scenario
 public class Mazing : Scenario
 {
 {
-    private Toplevel? _top;
+    private Window? _top;
     private MazeGenerator? _m;
     private MazeGenerator? _m;
 
 
     private List<Point>? _potions;
     private List<Point>? _potions;
@@ -33,17 +33,17 @@ public class Mazing : Scenario
         _top.KeyBindings.Add (Key.CursorDown, Command.Down);
         _top.KeyBindings.Add (Key.CursorDown, Command.Down);
 
 
         // Changing the key-bindings of a View is not allowed, however,
         // Changing the key-bindings of a View is not allowed, however,
-        // by default, Toplevel doesn't bind any of our movement keys, so
+        // by default, Runnable doesn't bind any of our movement keys, so
         // we can take advantage of the CommandNotBound event to handle them
         // we can take advantage of the CommandNotBound event to handle them
         // 
         // 
-        // An alternative implementation would be to create a TopLevel subclass that
+        // An alternative implementation would be to create a Runnable subclass that
         // calls AddCommand/KeyBindings.Add in the constructor. See the Snake game scenario
         // calls AddCommand/KeyBindings.Add in the constructor. See the Snake game scenario
         // for an example.
         // for an example.
         _top.CommandNotBound += TopCommandNotBound;
         _top.CommandNotBound += TopCommandNotBound;
 
 
         _top.DrawingContent += (s, _) =>
         _top.DrawingContent += (s, _) =>
                                {
                                {
-                                   if (s is not Toplevel top)
+                                   if (s is not Runnable top)
                                    {
                                    {
                                        return;
                                        return;
                                    }
                                    }
@@ -171,7 +171,7 @@ public class Mazing : Scenario
                 if (_m.PlayerHp <= 0)
                 if (_m.PlayerHp <= 0)
                 {
                 {
                     _message = "You died!";
                     _message = "You died!";
-                    Application.Current!.SetNeedsDraw (); // trigger redraw
+                    Application.TopRunnableView!.SetNeedsDraw (); // trigger redraw
                     _dead = true;
                     _dead = true;
 
 
                     return; // Stop further action if dead
                     return; // Stop further action if dead
@@ -190,7 +190,7 @@ public class Mazing : Scenario
                 _message = string.Empty;
                 _message = string.Empty;
             }
             }
 
 
-            Application.Current!.SetNeedsDraw (); // trigger redraw
+            Application.TopRunnableView!.SetNeedsDraw (); // trigger redraw
         }
         }
 
 
         // Optional win condition:
         // Optional win condition:
@@ -200,7 +200,7 @@ public class Mazing : Scenario
             _m = new (); // Generate a new maze
             _m = new (); // Generate a new maze
             _m.PlayerHp = hp;
             _m.PlayerHp = hp;
             GenerateNpcs ();
             GenerateNpcs ();
-            Application.Current!.SetNeedsDraw (); // trigger redraw
+            Application.TopRunnableView!.SetNeedsDraw (); // trigger redraw
         }
         }
     }
     }
 }
 }

+ 0 - 135
Examples/UICatalog/Scenarios/MenuBarScenario.cs

@@ -1,135 +0,0 @@
-using System;
-using static System.Runtime.InteropServices.JavaScript.JSType;
-
-namespace UICatalog.Scenarios;
-
-[ScenarioMetadata ("MenuBar", "Demonstrates the MenuBar using the demo menu.")]
-[ScenarioCategory ("Controls")]
-[ScenarioCategory ("Menus")]
-public class MenuBarScenario : Scenario
-{
-    private Label _currentMenuBarItem;
-    private Label _currentMenuItem;
-    private Label _focusedView;
-    private Label _lastAction;
-    private Label _lastKey;
-
-    public override void Main ()
-    {
-        // Init
-        Application.Init ();
-
-        // Setup - Create a top-level application window and configure it.
-        Window appWindow = new ()
-        {
-            Title = GetQuitKeyAndName (),
-            BorderStyle = LineStyle.None
-        };
-
-        MenuItem mbiCurrent = null;
-        MenuItem miCurrent = null;
-
-        var label = new Label { X = 0, Y = 10, Text = "Last Key: " };
-        appWindow.Add (label);
-
-        _lastKey = new Label { X = Pos.Right (label), Y = Pos.Top (label), Text = "" };
-
-        appWindow.Add (_lastKey);
-        label = new Label { X = 0, Y = Pos.Bottom (label), Text = "Current MenuBarItem: " };
-        appWindow.Add (label);
-
-        _currentMenuBarItem = new Label { X = Pos.Right (label), Y = Pos.Top (label), Text = "" };
-        appWindow.Add (_currentMenuBarItem);
-
-        label = new Label { X = 0, Y = Pos.Bottom (label), Text = "Current MenuItem: " };
-        appWindow.Add (label);
-
-        _currentMenuItem = new Label { X = Pos.Right (label), Y = Pos.Top (label), Text = "" };
-        appWindow.Add (_currentMenuItem);
-
-        label = new Label { X = 0, Y = Pos.Bottom (label), Text = "Last Action: " };
-        appWindow.Add (label);
-
-        _lastAction = new Label { X = Pos.Right (label), Y = Pos.Top (label), Text = "" };
-        appWindow.Add (_lastAction);
-
-        label = new Label { X = 0, Y = Pos.Bottom (label), Text = "Focused View: " };
-        appWindow.Add (label);
-
-        _focusedView = new Label { X = Pos.Right (label), Y = Pos.Top (label), Text = "" };
-        appWindow.Add (_focusedView);
-
-        MenuBar menuBar = new MenuBar ();
-        menuBar.UseKeysUpDownAsKeysLeftRight = true;
-        menuBar.Key = KeyCode.F9;
-        menuBar.Title = "TestMenuBar";
-
-        bool FnAction (string s)
-        {
-            _lastAction.Text = s;
-
-            return true;
-        }
-        
-        // Declare a variable for the function
-        Func<string, bool> fnActionVariable = FnAction;
-
-        menuBar.EnableForDesign (ref fnActionVariable);
-
-        menuBar.MenuOpening += (s, e) =>
-                               {
-                                   mbiCurrent = e.CurrentMenu;
-                                   SetCurrentMenuBarItem (mbiCurrent);
-                                   SetCurrentMenuItem (miCurrent);
-                                   _lastAction.Text = string.Empty;
-                               };
-
-        menuBar.MenuOpened += (s, e) =>
-                              {
-                                  miCurrent = e.MenuItem;
-                                  SetCurrentMenuBarItem (mbiCurrent);
-                                  SetCurrentMenuItem (miCurrent);
-                              };
-
-        menuBar.MenuClosing += (s, e) =>
-                               {
-                                   mbiCurrent = null;
-                                   miCurrent = null;
-                                   SetCurrentMenuBarItem (mbiCurrent);
-                                   SetCurrentMenuItem (miCurrent);
-                               };
-
-        Application.KeyDown += (s, e) =>
-                               {
-                                   _lastAction.Text = string.Empty;
-                                   _lastKey.Text = e.ToString ();
-                               };
-
-        // There's no focus change event, so this is a bit of a hack.
-        menuBar.SubViewsLaidOut += (s, e) => { _focusedView.Text = appWindow.MostFocused?.ToString () ?? "None"; };
-
-        var openBtn = new Button { X = Pos.Center (), Y = 4, Text = "_Open Menu", IsDefault = true };
-        openBtn.Accepting += (s, e) => { menuBar.OpenMenu (); };
-        appWindow.Add (openBtn);
-
-        var hideBtn = new Button { X = Pos.Center (), Y = Pos.Bottom (openBtn), Text = "Toggle Menu._Visible" };
-        hideBtn.Accepting += (s, e) => { menuBar.Visible = !menuBar.Visible; };
-        appWindow.Add (hideBtn);
-
-        var enableBtn = new Button { X = Pos.Center (), Y = Pos.Bottom (hideBtn), Text = "_Toggle Menu.Enable" };
-        enableBtn.Accepting += (s, e) => { menuBar.Enabled = !menuBar.Enabled; };
-        appWindow.Add (enableBtn);
-
-        appWindow.Add (menuBar);
-
-        // Run - Start the application.
-        Application.Run (appWindow);
-        appWindow.Dispose ();
-
-        // Shutdown - Calling Application.Shutdown is required.
-        Application.Shutdown ();
-    }
-
-    private void SetCurrentMenuBarItem (MenuItem mbi) { _currentMenuBarItem.Text = mbi != null ? mbi.Title : "Closed"; }
-    private void SetCurrentMenuItem (MenuItem mi) { _currentMenuItem.Text = mi != null ? mi.Title : "None"; }
-}

+ 5 - 5
Examples/UICatalog/Scenarios/Menus.cs

@@ -21,7 +21,7 @@ public class Menus : Scenario
         Logging.Logger = CreateLogger ();
         Logging.Logger = CreateLogger ();
 
 
         Application.Init ();
         Application.Init ();
-        Toplevel app = new ();
+        Runnable app = new ();
         app.Title = GetQuitKeyAndName ();
         app.Title = GetQuitKeyAndName ();
 
 
         ObservableCollection<string> eventSource = new ();
         ObservableCollection<string> eventSource = new ();
@@ -32,7 +32,7 @@ public class Menus : Scenario
             X = Pos.AnchorEnd (),
             X = Pos.AnchorEnd (),
             Width = Dim.Auto (),
             Width = Dim.Auto (),
             Height = Dim.Fill (), // Make room for some wide things
             Height = Dim.Fill (), // Make room for some wide things
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             Source = new ListWrapper<string> (eventSource)
             Source = new ListWrapper<string> (eventSource)
         };
         };
         eventLog.Border!.Thickness = new (0, 1, 0, 0);
         eventLog.Border!.Thickness = new (0, 1, 0, 0);
@@ -189,7 +189,7 @@ public class Menus : Scenario
             Application.KeyBindings.Remove (Key.F5);
             Application.KeyBindings.Remove (Key.F5);
             Application.KeyBindings.Add (Key.F5, this, Command.Edit);
             Application.KeyBindings.Add (Key.F5, this, Command.Edit);
 
 
-            var menuBar = new MenuBarv2
+            var menuBar = new MenuBar
             {
             {
                 Title = "MenuHost MenuBar"
                 Title = "MenuHost MenuBar"
             };
             };
@@ -257,7 +257,7 @@ public class Menus : Scenario
 
 
             menuBar.Accepted += (o, args) =>
             menuBar.Accepted += (o, args) =>
                                 {
                                 {
-                                    if (args.Context?.Source is MenuItemv2 mi && mi.CommandView == enableOverwriteMenuItemCb)
+                                    if (args.Context?.Source is MenuItem mi && mi.CommandView == enableOverwriteMenuItemCb)
                                     {
                                     {
                                         Logging.Debug ($"menuBar.Accepted: {args.Context.Source?.Title}");
                                         Logging.Debug ($"menuBar.Accepted: {args.Context.Source?.Title}");
 
 
@@ -302,7 +302,7 @@ public class Menus : Scenario
 
 
             menuBar.Accepted += (o, args) =>
             menuBar.Accepted += (o, args) =>
                                 {
                                 {
-                                    if (args.Context?.Source is MenuItemv2 mi && mi.CommandView == editModeMenuItemCb)
+                                    if (args.Context?.Source is MenuItem mi && mi.CommandView == editModeMenuItemCb)
                                     {
                                     {
                                         Logging.Debug ($"menuBar.Accepted: {args.Context.Source?.Title}");
                                         Logging.Debug ($"menuBar.Accepted: {args.Context.Source?.Title}");
 
 

+ 9 - 9
Examples/UICatalog/Scenarios/MessageBoxes.cs

@@ -251,7 +251,7 @@ public class MessageBoxes : Scenario
                                                {
                                                {
                                                    buttonPressedLabel.Text =
                                                    buttonPressedLabel.Text =
                                                        $"{MessageBox.Query (
                                                        $"{MessageBox.Query (
-                                                                             width,
+                                                                            ApplicationImpl.Instance, width,
                                                                              height,
                                                                              height,
                                                                              titleEdit.Text,
                                                                              titleEdit.Text,
                                                                              messageEdit.Text,
                                                                              messageEdit.Text,
@@ -263,14 +263,14 @@ public class MessageBoxes : Scenario
                                                else
                                                else
                                                {
                                                {
                                                    buttonPressedLabel.Text =
                                                    buttonPressedLabel.Text =
-                                                       $"{MessageBox.ErrorQuery (
-                                                                                  width,
-                                                                                  height,
-                                                                                  titleEdit.Text,
-                                                                                  messageEdit.Text,
-                                                                                  defaultButton,
-                                                                                  ckbWrapMessage.CheckedState == CheckState.Checked,
-                                                                                  btns.ToArray ()
+                                                       $"{MessageBox.ErrorQuery (ApplicationImpl.Instance,
+                                                                                 width,
+                                                                                 height,
+                                                                                 titleEdit.Text,
+                                                                                 messageEdit.Text,
+                                                                                 defaultButton,
+                                                                                 ckbWrapMessage.CheckedState == CheckState.Checked,
+                                                                                 btns.ToArray ()
                                                                                  )}";
                                                                                  )}";
                                                }
                                                }
                                            }
                                            }

+ 2 - 2
Examples/UICatalog/Scenarios/Mouse.cs

@@ -247,7 +247,7 @@ public class Mouse : Scenario
             Y = Pos.Bottom (label),
             Y = Pos.Bottom (label),
             Width = 50,
             Width = 50,
             Height = Dim.Fill (),
             Height = Dim.Fill (),
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             Source = new ListWrapper<string> (appLogList)
             Source = new ListWrapper<string> (appLogList)
         };
         };
         win.Add (label, appLog);
         win.Add (label, appLog);
@@ -278,7 +278,7 @@ public class Mouse : Scenario
             Y = Pos.Bottom (label),
             Y = Pos.Bottom (label),
             Width = Dim.Percent (50),
             Width = Dim.Percent (50),
             Height = Dim.Fill (),
             Height = Dim.Fill (),
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             Source = new ListWrapper<string> (winLogList)
             Source = new ListWrapper<string> (winLogList)
         };
         };
         win.Add (label, winLog);
         win.Add (label, winLog);

+ 82 - 73
Examples/UICatalog/Scenarios/MultiColouredTable.cs

@@ -1,4 +1,5 @@
-using System;
+#nullable enable
+
 using System.Data;
 using System.Data;
 using System.Text;
 using System.Text;
 
 
@@ -10,40 +11,49 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("TableView")]
 [ScenarioCategory ("TableView")]
 public class MultiColouredTable : Scenario
 public class MultiColouredTable : Scenario
 {
 {
-    private DataTable _table;
-    private TableViewColors _tableView;
+    private DataTable? _table;
+    private TableViewColors? _tableView;
 
 
     public override void Main ()
     public override void Main ()
     {
     {
-        // Init
         Application.Init ();
         Application.Init ();
 
 
-        // Setup - Create a top-level application window and configure it.
-        Toplevel appWindow = new ()
-        {
-            Title = GetQuitKeyAndName ()
-        };
-
-        _tableView = new () { X = 0, Y = 1, Width = Dim.Fill (), Height = Dim.Fill (1) };
-
-        var menu = new MenuBar
+        Window appWindow = new ()
         {
         {
-            Menus =
-            [
-                new ("_File", new MenuItem [] { new ("_Quit", "", Quit) })
-            ]
+            Title = GetQuitKeyAndName (),
+            BorderStyle = LineStyle.None,
         };
         };
-        appWindow.Add (menu);
 
 
-        var statusBar = new StatusBar (new Shortcut [] { new (Application.QuitKey, "Quit", Quit) });
-
-        appWindow.Add (statusBar);
-
-        appWindow.Add (_tableView);
+        // MenuBar
+        var menu = new MenuBar ();
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Action = Quit
+                                       }
+                                   ]
+                                  )
+                 );
+
+        _tableView = new () { X = 0, Y = Pos.Bottom (menu), Width = Dim.Fill (), Height = Dim.Fill (1) };
+
+        // StatusBar
+        var statusBar = new StatusBar (
+                                       [
+                                           new (Application.QuitKey, "Quit", Quit)
+                                       ]
+                                      );
+
+        appWindow.Add (menu, _tableView, statusBar);
 
 
         _tableView.CellActivated += EditCurrentCell;
         _tableView.CellActivated += EditCurrentCell;
 
 
-        var dt = new DataTable ();
+        DataTable dt = new ();
         dt.Columns.Add ("Col1");
         dt.Columns.Add ("Col1");
         dt.Columns.Add ("Col2");
         dt.Columns.Add ("Col2");
 
 
@@ -54,34 +64,33 @@ public class MultiColouredTable : Scenario
         dt.Rows.Add (DBNull.Value, DBNull.Value);
         dt.Rows.Add (DBNull.Value, DBNull.Value);
         dt.Rows.Add (DBNull.Value, DBNull.Value);
         dt.Rows.Add (DBNull.Value, DBNull.Value);
 
 
-        _tableView.SetScheme (new ()
-        {
-            Disabled = appWindow.GetAttributeForRole (VisualRole.Disabled),
-            HotFocus = appWindow.GetAttributeForRole (VisualRole.HotFocus),
-            Focus = appWindow.GetAttributeForRole (VisualRole.Focus),
-            Normal = new (Color.DarkGray, Color.Black)
-        });
+        _tableView.SetScheme (
+                              new ()
+                              {
+                                  Disabled = appWindow.GetAttributeForRole (VisualRole.Disabled),
+                                  HotFocus = appWindow.GetAttributeForRole (VisualRole.HotFocus),
+                                  Focus = appWindow.GetAttributeForRole (VisualRole.Focus),
+                                  Normal = new (Color.DarkGray, Color.Black)
+                              }
+                             );
 
 
         _tableView.Table = new DataTableSource (_table = dt);
         _tableView.Table = new DataTableSource (_table = dt);
 
 
-        // Run - Start the application.
         Application.Run (appWindow);
         Application.Run (appWindow);
         appWindow.Dispose ();
         appWindow.Dispose ();
-
-        // Shutdown - Calling Application.Shutdown is required.
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
-    private void EditCurrentCell (object sender, CellActivatedEventArgs e)
+    private void EditCurrentCell (object? sender, CellActivatedEventArgs e)
     {
     {
-        if (e.Table == null)
+        if (e.Table is null || _table is null || _tableView is null)
         {
         {
             return;
             return;
         }
         }
 
 
         var oldValue = e.Table [e.Row, e.Col].ToString ();
         var oldValue = e.Table [e.Row, e.Col].ToString ();
 
 
-        if (GetText ("Enter new value", e.Table.ColumnNames [e.Col], oldValue, out string newText))
+        if (GetText ("Enter new value", e.Table.ColumnNames [e.Col], oldValue ?? "", out string newText))
         {
         {
             try
             try
             {
             {
@@ -90,7 +99,7 @@ public class MultiColouredTable : Scenario
             }
             }
             catch (Exception ex)
             catch (Exception ex)
             {
             {
-                MessageBox.ErrorQuery (60, 20, "Failed to set text", ex.Message, "Ok");
+                MessageBox.ErrorQuery (ApplicationImpl.Instance, 60, 20, "Failed to set text", ex.Message, "Ok");
             }
             }
 
 
             _tableView.Update ();
             _tableView.Update ();
@@ -101,20 +110,20 @@ public class MultiColouredTable : Scenario
     {
     {
         var okPressed = false;
         var okPressed = false;
 
 
-        var ok = new Button { Text = "Ok", IsDefault = true };
+        Button ok = new () { Text = "Ok", IsDefault = true };
 
 
         ok.Accepting += (s, e) =>
         ok.Accepting += (s, e) =>
-                     {
-                         okPressed = true;
-                         Application.RequestStop ();
-                     };
-        var cancel = new Button { Text = "Cancel" };
+                        {
+                            okPressed = true;
+                            Application.RequestStop ();
+                        };
+        Button cancel = new () { Text = "Cancel" };
         cancel.Accepting += (s, e) => { Application.RequestStop (); };
         cancel.Accepting += (s, e) => { Application.RequestStop (); };
-        var d = new Dialog { Title = title, Buttons = [ok, cancel] };
+        Dialog d = new () { Title = title, Buttons = [ok, cancel] };
 
 
-        var lbl = new Label { X = 0, Y = 1, Text = label };
+        Label lbl = new () { X = 0, Y = 1, Text = label };
 
 
-        var tf = new TextField { Text = initialText, X = 0, Y = 2, Width = Dim.Fill () };
+        TextField tf = new () { Text = initialText, X = 0, Y = 2, Width = Dim.Fill () };
 
 
         d.Add (lbl, tf);
         d.Add (lbl, tf);
         tf.SetFocus ();
         tf.SetFocus ();
@@ -122,7 +131,7 @@ public class MultiColouredTable : Scenario
         Application.Run (d);
         Application.Run (d);
         d.Dispose ();
         d.Dispose ();
 
 
-        enteredText = okPressed ? tf.Text : null;
+        enteredText = okPressed ? tf.Text : string.Empty;
 
 
         return okPressed;
         return okPressed;
     }
     }
@@ -155,20 +164,20 @@ public class MultiColouredTable : Scenario
                             break;
                             break;
                         case 1:
                         case 1:
                             SetAttribute (
                             SetAttribute (
-                                                 new (
-                                                      Color.BrightRed,
-                                                      cellColor.Background
-                                                     )
-                                                );
+                                          new (
+                                               Color.BrightRed,
+                                               cellColor.Background
+                                              )
+                                         );
 
 
                             break;
                             break;
                         case 2:
                         case 2:
                             SetAttribute (
                             SetAttribute (
-                                                 new (
-                                                      Color.BrightYellow,
-                                                      cellColor.Background
-                                                     )
-                                                );
+                                          new (
+                                               Color.BrightYellow,
+                                               cellColor.Background
+                                              )
+                                         );
 
 
                             break;
                             break;
                         case 3:
                         case 3:
@@ -177,29 +186,29 @@ public class MultiColouredTable : Scenario
                             break;
                             break;
                         case 4:
                         case 4:
                             SetAttribute (
                             SetAttribute (
-                                                 new (
-                                                      Color.BrightGreen,
-                                                      cellColor.Background
-                                                     )
-                                                );
+                                          new (
+                                               Color.BrightGreen,
+                                               cellColor.Background
+                                              )
+                                         );
 
 
                             break;
                             break;
                         case 5:
                         case 5:
                             SetAttribute (
                             SetAttribute (
-                                                 new (
-                                                      Color.BrightBlue,
-                                                      cellColor.Background
-                                                     )
-                                                );
+                                          new (
+                                               Color.BrightBlue,
+                                               cellColor.Background
+                                              )
+                                         );
 
 
                             break;
                             break;
                         case 6:
                         case 6:
                             SetAttribute (
                             SetAttribute (
-                                                 new (
-                                                      Color.BrightCyan,
-                                                      cellColor.Background
-                                                     )
-                                                );
+                                          new (
+                                               Color.BrightCyan,
+                                               cellColor.Background
+                                              )
+                                         );
 
 
                             break;
                             break;
                         case 7:
                         case 7:

+ 4 - 4
Examples/UICatalog/Scenarios/Navigation.cs

@@ -59,7 +59,7 @@ public class Navigation : Scenario
             Y = 0,
             Y = 0,
             Title = $"TopButton _{GetNextHotKey ()}"
             Title = $"TopButton _{GetNextHotKey ()}"
         };
         };
-        button.Accepting += (sender, args) => MessageBox.Query ("hi", button.Title, "_Ok");
+        button.Accepting += (sender, args) => MessageBox.Query (ApplicationImpl.Instance, "hi", button.Title, "_Ok");
 
 
         testFrame.Add (button);
         testFrame.Add (button);
 
 
@@ -180,7 +180,7 @@ public class Navigation : Scenario
             X = 1,
             X = 1,
             Y = 7,
             Y = 7,
             Id = "datePicker",
             Id = "datePicker",
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             ShadowStyle = ShadowStyle.Transparent,
             ShadowStyle = ShadowStyle.Transparent,
             BorderStyle = LineStyle.Double,
             BorderStyle = LineStyle.Double,
             CanFocus = true, // Can't drag without this? BUGBUG
             CanFocus = true, // Can't drag without this? BUGBUG
@@ -210,7 +210,7 @@ public class Navigation : Scenario
 
 
         return;
         return;
 
 
-        void OnApplicationIteration (object sender, IterationEventArgs args)
+        void OnApplicationIteration (object sender, EventArgs<IApplication> args)
         {
         {
             if (progressBar.Fraction == 1.0)
             if (progressBar.Fraction == 1.0)
             {
             {
@@ -237,7 +237,7 @@ public class Navigation : Scenario
             Height = Dim.Auto (),
             Height = Dim.Auto (),
             Width = Dim.Auto (),
             Width = Dim.Auto (),
             Title = $"Overlapped{id} _{GetNextHotKey ()}",
             Title = $"Overlapped{id} _{GetNextHotKey ()}",
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             Id = $"Overlapped{id}",
             Id = $"Overlapped{id}",
             ShadowStyle = ShadowStyle.Transparent,
             ShadowStyle = ShadowStyle.Transparent,
             BorderStyle = LineStyle.Double,
             BorderStyle = LineStyle.Double,

+ 154 - 108
Examples/UICatalog/Scenarios/Notepad.cs

@@ -1,4 +1,5 @@
 #nullable enable
 #nullable enable
+
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
 
 
 [ScenarioMetadata ("Notepad", "Multi-tab text editor using the TabView control.")]
 [ScenarioMetadata ("Notepad", "Multi-tab text editor using the TabView control.")]
@@ -16,41 +17,65 @@ public class Notepad : Scenario
     {
     {
         Application.Init ();
         Application.Init ();
 
 
-        Toplevel top = new ();
-
-        var menu = new MenuBar
+        Window top = new ()
         {
         {
-            Menus =
-            [
-                new (
-                     "_File",
-                     new MenuItem []
-                     {
-                         new (
-                              "_New",
-                              "",
-                              () => New (),
-                              null,
-                              null,
-                              KeyCode.N
-                              | KeyCode.CtrlMask
-                              | KeyCode.AltMask
-                             ),
-                         new ("_Open", "", Open),
-                         new ("_Save", "", Save),
-                         new ("Save _As", "", () => SaveAs ()),
-                         new ("_Close", "", Close),
-                         new ("_Quit", "", Quit)
-                     }
-                    ),
-                new (
-                     "_About",
-                     "",
-                     () => MessageBox.Query ("Notepad", "About Notepad...", "Ok")
-                    )
-            ]
+            BorderStyle = LineStyle.None,
         };
         };
-        top.Add (menu);
+
+        // MenuBar
+        MenuBar menu = new ();
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_New",
+                                           Key = Key.N.WithCtrl.WithAlt,
+                                           Action = New
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Open",
+                                           Action = Open
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Save",
+                                           Action = Save
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "Save _As",
+                                           Action = () => SaveAs ()
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Close",
+                                           Action = Close
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Action = Quit
+                                       }
+                                   ]
+                                  )
+                 );
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_About",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_About",
+                                           Action = () => MessageBox.Query (ApplicationImpl.Instance,  "Notepad", "About Notepad...", "Ok")
+                                       }
+                                   ]
+                                  )
+                 );
 
 
         _tabView = CreateNewTabView ();
         _tabView = CreateNewTabView ();
 
 
@@ -58,84 +83,85 @@ public class Notepad : Scenario
         _tabView.ApplyStyleChanges ();
         _tabView.ApplyStyleChanges ();
 
 
         _tabView.X = 0;
         _tabView.X = 0;
-        _tabView.Y = 1;
+        _tabView.Y = Pos.Bottom (menu);
         _tabView.Width = Dim.Fill ();
         _tabView.Width = Dim.Fill ();
         _tabView.Height = Dim.Fill (1);
         _tabView.Height = Dim.Fill (1);
 
 
-        top.Add (_tabView);
         LenShortcut = new (Key.Empty, "Len: ", null);
         LenShortcut = new (Key.Empty, "Len: ", null);
 
 
-        var statusBar = new StatusBar (
-                                       [
-                                           new (Application.QuitKey, "Quit", Quit),
-                                           new (Key.F2, "Open", Open),
-                                           new (Key.F1, "New", New),
-                                           new (Key.F3, "Save", Save),
-                                           new (Key.F6, "Close", Close),
-                                           LenShortcut
-                                       ]
-                                      )
+        // StatusBar
+        StatusBar statusBar = new (
+                                   [
+                                       new (Application.QuitKey, "Quit", Quit),
+                                       new (Key.F2, "Open", Open),
+                                       new (Key.F1, "New", New),
+                                       new (Key.F3, "Save", Save),
+                                       new (Key.F6, "Close", Close),
+                                       LenShortcut
+                                   ]
+                                  )
         {
         {
             AlignmentModes = AlignmentModes.IgnoreFirstOrLast
             AlignmentModes = AlignmentModes.IgnoreFirstOrLast
         };
         };
-        top.Add (statusBar);
+
+        top.Add (menu, _tabView, statusBar);
 
 
         _focusedTabView = _tabView;
         _focusedTabView = _tabView;
         _tabView.SelectedTabChanged += TabView_SelectedTabChanged;
         _tabView.SelectedTabChanged += TabView_SelectedTabChanged;
         _tabView.HasFocusChanging += (s, e) => _focusedTabView = _tabView;
         _tabView.HasFocusChanging += (s, e) => _focusedTabView = _tabView;
 
 
-        top.Ready += (s, e) =>
+        top.IsModalChanged += (s, e) =>
                      {
                      {
-                         New ();
-                         LenShortcut.Title = $"Len:{_focusedTabView.Text?.Length ?? 0}";
+                         if (e.Value)
+                         {
+                             New ();
+                             LenShortcut.Title = $"Len:{_focusedTabView?.Text?.Length ?? 0}";
+                         }
                      };
                      };
 
 
         Application.Run (top);
         Application.Run (top);
         top.Dispose ();
         top.Dispose ();
-
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
-    public void Save () { Save (_focusedTabView!, _focusedTabView!.SelectedTab!); }
+    public void Save ()
+    {
+        if (_focusedTabView?.SelectedTab is { })
+        {
+            Save (_focusedTabView, _focusedTabView.SelectedTab);
+        }
+    }
 
 
     public void Save (TabView tabViewToSave, Tab tabToSave)
     public void Save (TabView tabViewToSave, Tab tabToSave)
     {
     {
-        var tab = tabToSave as OpenedFile;
-
-        if (tab == null)
+        if (tabToSave is not OpenedFile tab)
         {
         {
             return;
             return;
         }
         }
 
 
-        if (tab.File == null)
+        if (tab.File is null)
         {
         {
             SaveAs ();
             SaveAs ();
         }
         }
+        else
+        {
+            tab.Save ();
+        }
 
 
-        tab.Save ();
         tabViewToSave.SetNeedsDraw ();
         tabViewToSave.SetNeedsDraw ();
     }
     }
 
 
     public bool SaveAs ()
     public bool SaveAs ()
     {
     {
-        var tab = _focusedTabView!.SelectedTab as OpenedFile;
-
-        if (tab == null)
+        if (_focusedTabView?.SelectedTab is not OpenedFile tab)
         {
         {
             return false;
             return false;
         }
         }
 
 
-        var fd = new SaveDialog ();
+        SaveDialog fd = new ();
         Application.Run (fd);
         Application.Run (fd);
 
 
-        if (string.IsNullOrWhiteSpace (fd.Path))
-        {
-            fd.Dispose ();
-
-            return false;
-        }
-
-        if (fd.Canceled)
+        if (string.IsNullOrWhiteSpace (fd.Path) || fd.Canceled)
         {
         {
             fd.Dispose ();
             fd.Dispose ();
 
 
@@ -151,13 +177,17 @@ public class Notepad : Scenario
         return true;
         return true;
     }
     }
 
 
-    private void Close () { Close (_focusedTabView!, _focusedTabView!.SelectedTab!); }
+    private void Close ()
+    {
+        if (_focusedTabView?.SelectedTab is { })
+        {
+            Close (_focusedTabView, _focusedTabView.SelectedTab);
+        }
+    }
 
 
     private void Close (TabView tv, Tab tabToClose)
     private void Close (TabView tv, Tab tabToClose)
     {
     {
-        var tab = tabToClose as OpenedFile;
-
-        if (tab == null)
+        if (tabToClose is not OpenedFile tab)
         {
         {
             return;
             return;
         }
         }
@@ -166,15 +196,15 @@ public class Notepad : Scenario
 
 
         if (tab.UnsavedChanges)
         if (tab.UnsavedChanges)
         {
         {
-            int result = MessageBox.Query (
-                                           "Save Changes",
-                                           $"Save changes to {tab.Text.TrimEnd ('*')}",
-                                           "Yes",
-                                           "No",
-                                           "Cancel"
+            int? result = MessageBox.Query (ApplicationImpl.Instance,
+                                            "Save Changes",
+                                            $"Save changes to {tab.Text.TrimEnd ('*')}",
+                                            "Yes",
+                                            "No",
+                                            "Cancel"
                                           );
                                           );
 
 
-            if (result == -1 || result == 2)
+            if (result is null || result == 2)
             {
             {
                 // user cancelled
                 // user cancelled
                 return;
                 return;
@@ -182,7 +212,7 @@ public class Notepad : Scenario
 
 
             if (result == 0)
             if (result == 0)
             {
             {
-                if (tab.File == null)
+                if (tab.File is null)
                 {
                 {
                     SaveAs ();
                     SaveAs ();
                 }
                 }
@@ -207,7 +237,7 @@ public class Notepad : Scenario
 
 
     private TabView CreateNewTabView ()
     private TabView CreateNewTabView ()
     {
     {
-        var tv = new TabView { X = 0, Y = 0, Width = Dim.Fill (), Height = Dim.Fill () };
+        TabView tv = new () { X = 0, Y = 0, Width = Dim.Fill (), Height = Dim.Fill () };
 
 
         tv.TabClicked += TabView_TabClicked;
         tv.TabClicked += TabView_TabClicked;
         tv.SelectedTabChanged += TabView_SelectedTabChanged;
         tv.SelectedTabChanged += TabView_SelectedTabChanged;
@@ -220,7 +250,7 @@ public class Notepad : Scenario
 
 
     private void Open ()
     private void Open ()
     {
     {
-        var open = new OpenDialog { Title = "Open", AllowsMultipleSelection = true };
+        OpenDialog open = new () { Title = "Open", AllowsMultipleSelection = true };
 
 
         Application.Run (open);
         Application.Run (open);
 
 
@@ -246,21 +276,29 @@ public class Notepad : Scenario
     /// <summary>Creates a new tab with initial text</summary>
     /// <summary>Creates a new tab with initial text</summary>
     /// <param name="fileInfo">File that was read or null if a new blank document</param>
     /// <param name="fileInfo">File that was read or null if a new blank document</param>
     /// <param name="tabName"></param>
     /// <param name="tabName"></param>
-    private void Open (FileInfo fileInfo, string tabName)
+    private void Open (FileInfo? fileInfo, string tabName)
     {
     {
-        var tab = new OpenedFile (this) { DisplayText = tabName, File = fileInfo };
+        if (_focusedTabView is null)
+        {
+            return;
+        }
+
+        OpenedFile tab = new (this) { DisplayText = tabName, File = fileInfo };
         tab.View = tab.CreateTextView (fileInfo);
         tab.View = tab.CreateTextView (fileInfo);
         tab.SavedText = tab.View.Text;
         tab.SavedText = tab.View.Text;
-        tab.RegisterTextViewEvents (_focusedTabView!);
+        tab.RegisterTextViewEvents (_focusedTabView);
 
 
-        _focusedTabView!.AddTab (tab, true);
+        _focusedTabView.AddTab (tab, true);
     }
     }
 
 
     private void Quit () { Application.RequestStop (); }
     private void Quit () { Application.RequestStop (); }
 
 
     private void TabView_SelectedTabChanged (object? sender, TabChangedEventArgs e)
     private void TabView_SelectedTabChanged (object? sender, TabChangedEventArgs e)
     {
     {
-        LenShortcut!.Title = $"Len:{e.NewTab?.View?.Text?.Length ?? 0}";
+        if (LenShortcut is { })
+        {
+            LenShortcut.Title = $"Len:{e.NewTab?.View?.Text?.Length ?? 0}";
+        }
 
 
         e.NewTab?.View?.SetFocus ();
         e.NewTab?.View?.SetFocus ();
     }
     }
@@ -275,30 +313,33 @@ public class Notepad : Scenario
 
 
         View [] items;
         View [] items;
 
 
-        if (e.Tab == null)
+        if (e.Tab is null)
         {
         {
-            items = [new MenuItemv2 ("Open", "", Open)];
+            items = [new MenuItem { Title = "Open", Action = Open }];
         }
         }
         else
         else
         {
         {
             var tv = (TabView)sender!;
             var tv = (TabView)sender!;
-            var t = (OpenedFile)e.Tab;
 
 
             items =
             items =
             [
             [
-                new MenuItemv2 ("Save", "", () => Save (_focusedTabView!, e.Tab)),
-                new MenuItemv2 ("Close", "", () => Close (tv, e.Tab))
+                new MenuItem { Title = "Save", Action = () => Save (_focusedTabView!, e.Tab) },
+                new MenuItem { Title = "Close", Action = () => Close (tv, e.Tab) }
             ];
             ];
+        }
 
 
-            PopoverMenu? contextMenu = new (items);
-
-            // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
-            // and the context menu is disposed when it is closed.
-            tv.App!.Popover?.Register (contextMenu);
-            contextMenu?.MakeVisible (e.MouseEvent.ScreenPosition);
+        PopoverMenu contextMenu = new (items);
 
 
-            e.MouseEvent.Handled = true;
+        // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
+        // and the context menu is disposed when it is closed.
+        if (sender is TabView tabView && tabView.App?.Popover is { })
+        {
+            tabView.App.Popover.Register (contextMenu);
         }
         }
+
+        contextMenu.MakeVisible (e.MouseEvent.ScreenPosition);
+
+        e.MouseEvent.Handled = true;
     }
     }
 
 
     private class OpenedFile (Notepad notepad) : Tab
     private class OpenedFile (Notepad notepad) : Tab
@@ -307,8 +348,8 @@ public class Notepad : Scenario
 
 
         public OpenedFile CloneTo (TabView other)
         public OpenedFile CloneTo (TabView other)
         {
         {
-            var newTab = new OpenedFile (_notepad) { DisplayText = base.Text, File = File };
-            newTab.View = newTab.CreateTextView (newTab.File!);
+            OpenedFile newTab = new (_notepad) { DisplayText = Text, File = File };
+            newTab.View = newTab.CreateTextView (newTab.File);
             newTab.SavedText = newTab.View.Text;
             newTab.SavedText = newTab.View.Text;
             newTab.RegisterTextViewEvents (other);
             newTab.RegisterTextViewEvents (other);
             other.AddTab (newTab, true);
             other.AddTab (newTab, true);
@@ -340,7 +381,10 @@ public class Notepad : Scenario
 
 
         public void RegisterTextViewEvents (TabView parent)
         public void RegisterTextViewEvents (TabView parent)
         {
         {
-            var textView = (TextView)View!;
+            if (View is not TextView textView)
+            {
+                return;
+            }
 
 
             // when user makes changes rename tab to indicate unsaved
             // when user makes changes rename tab to indicate unsaved
             textView.ContentsChanged += (s, k) =>
             textView.ContentsChanged += (s, k) =>
@@ -363,25 +407,27 @@ public class Notepad : Scenario
                                                 }
                                                 }
                                             }
                                             }
 
 
-                                            _notepad.LenShortcut!.Title = $"Len:{textView.Text.Length}";
+                                            if (_notepad.LenShortcut is { })
+                                            {
+                                                _notepad.LenShortcut.Title = $"Len:{textView.Text.Length}";
+                                            }
                                         };
                                         };
         }
         }
 
 
         /// <summary>The text of the tab the last time it was saved</summary>
         /// <summary>The text of the tab the last time it was saved</summary>
-        /// <value></value>
         public string? SavedText { get; set; }
         public string? SavedText { get; set; }
 
 
-        public bool UnsavedChanges => !string.Equals (SavedText, View!.Text);
+        public bool UnsavedChanges => View is { } && !string.Equals (SavedText, View.Text);
 
 
         internal void Save ()
         internal void Save ()
         {
         {
-            string newText = View!.Text;
-
-            if (File is null || string.IsNullOrWhiteSpace (File.FullName))
+            if (View is null || File is null || string.IsNullOrWhiteSpace (File.FullName))
             {
             {
                 return;
                 return;
             }
             }
 
 
+            string newText = View.Text;
+
             System.IO.File.WriteAllText (File.FullName, newText);
             System.IO.File.WriteAllText (File.FullName, newText);
             SavedText = newText;
             SavedText = newText;
 
 

+ 1 - 1
Examples/UICatalog/Scenarios/PosAlignDemo.cs

@@ -20,7 +20,7 @@ public sealed class PosAlignDemo : Scenario
             Title = $"{Application.QuitKey} to Quit - Scenario: {GetName ()} - {GetDescription ()}"
             Title = $"{Application.QuitKey} to Quit - Scenario: {GetName ()} - {GetDescription ()}"
         };
         };
 
 
-        SetupControls (appWindow, Dimension.Width, Schemes.Toplevel);
+        SetupControls (appWindow, Dimension.Width, Schemes.Runnable);
 
 
         SetupControls (appWindow, Dimension.Height, Schemes.Error);
         SetupControls (appWindow, Dimension.Height, Schemes.Error);
 
 

+ 14 - 10
Examples/UICatalog/Scenarios/ProgressBarStyles.cs

@@ -27,7 +27,7 @@ public class ProgressBarStyles : Scenario
     {
     {
         Application.Init ();
         Application.Init ();
 
 
-        Window app = new ()
+        Window win = new ()
         {
         {
             Title = GetQuitKeyAndName (), BorderStyle = LineStyle.Single,
             Title = GetQuitKeyAndName (), BorderStyle = LineStyle.Single,
         };
         };
@@ -38,7 +38,7 @@ public class ProgressBarStyles : Scenario
             ShowViewIdentifier = true
             ShowViewIdentifier = true
 
 
         };
         };
-        app.Add (editor);
+        win.Add (editor);
 
 
         View container = new ()
         View container = new ()
         {
         {
@@ -47,7 +47,7 @@ public class ProgressBarStyles : Scenario
             Width = Dim.Fill (),
             Width = Dim.Fill (),
             Height = Dim.Fill (),
             Height = Dim.Fill (),
         };
         };
-        app.Add (container);
+        win.Add (container);
 
 
         const float fractionStep = 0.01F;
         const float fractionStep = 0.01F;
 
 
@@ -278,8 +278,8 @@ public class ProgressBarStyles : Scenario
 
 
 
 
 
 
-        app.Initialized += App_Initialized;
-        app.Unloaded += App_Unloaded;
+        win.Initialized += Win_Initialized;
+        win.IsRunningChanged += Win_IsRunningChanged;
 
 
         _pulseTimer = new Timer (
         _pulseTimer = new Timer (
                                  _ =>
                                  _ =>
@@ -292,14 +292,18 @@ public class ProgressBarStyles : Scenario
                                  0,
                                  0,
                                  300
                                  300
                                 );
                                 );
-        Application.Run (app);
-        app.Dispose ();
+        Application.Run (win);
+        win.Dispose ();
         Application.Shutdown ();
         Application.Shutdown ();
 
 
         return;
         return;
 
 
-        void App_Unloaded (object sender, EventArgs args)
+        void Win_IsRunningChanged (object sender, EventArgs<bool> args)
         {
         {
+            if (args.Value)
+            {
+                return;
+            }
             if (_fractionTimer != null)
             if (_fractionTimer != null)
             {
             {
                 _fractionTimer.Dispose ();
                 _fractionTimer.Dispose ();
@@ -312,11 +316,11 @@ public class ProgressBarStyles : Scenario
                 _pulseTimer = null;
                 _pulseTimer = null;
             }
             }
 
 
-            app.Unloaded -= App_Unloaded;
+            win.IsRunningChanged -= Win_IsRunningChanged;
         }
         }
     }
     }
 
 
-    private void App_Initialized (object sender, EventArgs e)
+    private void Win_Initialized (object sender, EventArgs e)
     {
     {
         _pbList.SelectedItem = 0;
         _pbList.SelectedItem = 0;
     }
     }

+ 4 - 4
Examples/UICatalog/Scenarios/RunTExample.cs

@@ -8,7 +8,7 @@ public class RunTExample : Scenario
     public override void Main ()
     public override void Main ()
     {
     {
         // No need to call Init if Application.Run<T> is used
         // No need to call Init if Application.Run<T> is used
-        Application.Run<ExampleWindow> ().Dispose ();
+        Application.Run<ExampleWindow> ();
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
@@ -63,12 +63,12 @@ public class RunTExample : Scenario
                                {
                                {
                                    if (_usernameText.Text == "admin" && passwordText.Text == "password")
                                    if (_usernameText.Text == "admin" && passwordText.Text == "password")
                                    {
                                    {
-                                       MessageBox.Query ("Login Successful", $"Username: {_usernameText.Text}", "Ok");
-                                       Application.RequestStop ();
+                                       MessageBox.Query (App, "Login Successful", $"Username: {_usernameText.Text}", "Ok");
+                                       App?.RequestStop ();
                                    }
                                    }
                                    else
                                    else
                                    {
                                    {
-                                       MessageBox.ErrorQuery (
+                                       MessageBox.ErrorQuery (App,
                                                               "Error Logging In",
                                                               "Error Logging In",
                                                               "Incorrect username or password (hint: admin/password)",
                                                               "Incorrect username or password (hint: admin/password)",
                                                               "Ok"
                                                               "Ok"

+ 177 - 74
Examples/UICatalog/Scenarios/RuneWidthGreaterThanOne.cs

@@ -1,4 +1,6 @@
-using System;
+#nullable enable
+
+using System;
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
 
 
@@ -8,99 +10,173 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("Tests")]
 [ScenarioCategory ("Tests")]
 public class RuneWidthGreaterThanOne : Scenario
 public class RuneWidthGreaterThanOne : Scenario
 {
 {
-    private Button _button;
-    private Label _label;
-    private Label _labelR;
-    private Label _labelV;
-    private string _lastRunesUsed;
-    private TextField _text;
-    private Window _win;
+    private Button? _button;
+    private Label? _label;
+    private Label? _labelR;
+    private Label? _labelV;
+    private string? _lastRunesUsed;
+    private TextField? _text;
+    private Window? _win;
 
 
     public override void Main ()
     public override void Main ()
     {
     {
         Application.Init ();
         Application.Init ();
 
 
-        Toplevel topLevel = new ();
+        // Window (top-level)
+        Window win = new ()
+        {
+            X = 5,
+            Y = 5,
+            Width = Dim.Fill (22),
+            Height = Dim.Fill (5),
+            Arrangement = ViewArrangement.Overlapped | ViewArrangement.Movable
+        };
+        _win = win;
+
+        // MenuBar
+        MenuBar menu = new ();
+
+        // Controls
+        _label = new ()
+        {
+            X = Pos.Center (),
+            Y = 1
+        };
+
+        _text = new ()
+        {
+            X = Pos.Center (),
+            Y = 3,
+            Width = 20
+        };
 
 
-        var menu = new MenuBar
+        _button = new ()
         {
         {
-            Menus =
-            [
-                new MenuBarItem (
-                                 "Padding",
-                                 new MenuItem []
-                                 {
-                                     new (
-                                          "With Padding",
-                                          "",
-                                          () => _win.Padding.Thickness =
-                                                    new Thickness (1)
-                                         ),
-                                     new (
-                                          "Without Padding",
-                                          "",
-                                          () => _win.Padding.Thickness =
-                                                    new Thickness (0)
-                                         )
-                                 }
-                                ),
-                new MenuBarItem (
-                                 "BorderStyle",
-                                 new MenuItem []
-                                 {
-                                     new (
-                                          "Single",
-                                          "",
-                                          () => _win.BorderStyle = LineStyle.Single
-                                         ),
-                                     new (
-                                          "None",
-                                          "",
-                                          () => _win.BorderStyle = LineStyle.None
-                                         )
-                                 }
-                                ),
-                new MenuBarItem (
-                                 "Runes length",
-                                 new MenuItem []
-                                 {
-                                     new ("Wide", "", WideRunes),
-                                     new ("Narrow", "", NarrowRunes),
-                                     new ("Mixed", "", MixedRunes)
-                                 }
-                                )
-            ]
+            X = Pos.Center (),
+            Y = 5
         };
         };
 
 
-        _label = new Label
+        _labelR = new ()
         {
         {
-            X = Pos.Center (), Y = 1,
+            X = Pos.AnchorEnd (30),
+            Y = 18
         };
         };
-        _text = new TextField { X = Pos.Center (), Y = 3, Width = 20 };
-        _button = new Button { X = Pos.Center (), Y = 5 };
-        _labelR = new Label { X = Pos.AnchorEnd (30), Y = 18 };
 
 
-        _labelV = new Label
+        _labelV = new ()
         {
         {
-            TextDirection = TextDirection.TopBottom_LeftRight, X = Pos.AnchorEnd (30), Y = Pos.Bottom (_labelR)
+            TextDirection = TextDirection.TopBottom_LeftRight,
+            X = Pos.AnchorEnd (30),
+            Y = Pos.Bottom (_labelR)
         };
         };
-        _win = new Window { X = 5, Y = 5, Width = Dim.Fill (22), Height = Dim.Fill (5) };
-        _win.Add (_label, _text, _button, _labelR, _labelV);
-        topLevel.Add (menu, _win);
+
+        menu.Add (
+            new MenuBarItem (
+                "Padding",
+                [
+                    new MenuItem
+                    {
+                        Title = "With Padding",
+                        Action = () =>
+                        {
+                            if (_win is { })
+                            {
+                                _win.Padding!.Thickness = new (1);
+                            }
+                        }
+                    },
+                    new MenuItem
+                    {
+                        Title = "Without Padding",
+                        Action = () =>
+                        {
+                            if (_win is { })
+                            {
+                                _win.Padding!.Thickness = new (0);
+                            }
+                        }
+                    }
+                ]
+            )
+        );
+
+        menu.Add (
+            new MenuBarItem (
+                "BorderStyle",
+                [
+                    new MenuItem
+                    {
+                        Title = "Single",
+                        Action = () =>
+                        {
+                            if (_win is { })
+                            {
+                                _win.BorderStyle = LineStyle.Single;
+                            }
+                        }
+                    },
+                    new MenuItem
+                    {
+                        Title = "None",
+                        Action = () =>
+                        {
+                            if (_win is { })
+                            {
+                                _win.BorderStyle = LineStyle.None;
+                            }
+                        }
+                    }
+                ]
+            )
+        );
+
+        menu.Add (
+            new MenuBarItem (
+                "Runes length",
+                [
+                    new MenuItem
+                    {
+                        Title = "Wide",
+                        Action = WideRunes
+                    },
+                    new MenuItem
+                    {
+                        Title = "Narrow",
+                        Action = NarrowRunes
+                    },
+                    new MenuItem
+                    {
+                        Title = "Mixed",
+                        Action = MixedRunes
+                    }
+                ]
+            )
+        );
+
+        // Add views in order of visual appearance
+        win.Add (menu, _label, _text, _button, _labelR, _labelV);
 
 
         WideRunes ();
         WideRunes ();
 
 
-        //NarrowRunes ();
-        //MixedRunes ();
-        Application.Run (topLevel);
-        topLevel.Dispose ();
+        Application.Run (win);
+        win.Dispose ();
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
-    private void MixedMessage (object sender, EventArgs e) { MessageBox.Query ("Say Hello 你", $"Hello {_text.Text}", "Ok"); }
+    private void MixedMessage (object? sender, EventArgs e)
+    {
+        if (_text is { })
+        {
+            MessageBox.Query (ApplicationImpl.Instance, "Say Hello 你", $"Hello {_text.Text}", "Ok");
+        }
+    }
 
 
     private void MixedRunes ()
     private void MixedRunes ()
     {
     {
+        if (_label is null || _text is null || _button is null || _labelR is null || _labelV is null || _win is null)
+        {
+            return;
+        }
+
         UnsetClickedEvent ();
         UnsetClickedEvent ();
         _label.Text = "Enter your name 你:";
         _label.Text = "Enter your name 你:";
         _text.Text = "gui.cs 你:";
         _text.Text = "gui.cs 你:";
@@ -117,10 +193,21 @@ public class RuneWidthGreaterThanOne : Scenario
         Application.LayoutAndDraw ();
         Application.LayoutAndDraw ();
     }
     }
 
 
-    private void NarrowMessage (object sender, EventArgs e) { MessageBox.Query ("Say Hello", $"Hello {_text.Text}", "Ok"); }
+    private void NarrowMessage (object? sender, EventArgs e)
+    {
+        if (_text is { })
+        {
+            MessageBox.Query (ApplicationImpl.Instance, "Say Hello", $"Hello {_text.Text}", "Ok");
+        }
+    }
 
 
     private void NarrowRunes ()
     private void NarrowRunes ()
     {
     {
+        if (_label is null || _text is null || _button is null || _labelR is null || _labelV is null || _win is null)
+        {
+            return;
+        }
+
         UnsetClickedEvent ();
         UnsetClickedEvent ();
         _label.Text = "Enter your name:";
         _label.Text = "Enter your name:";
         _text.Text = "gui.cs";
         _text.Text = "gui.cs";
@@ -139,6 +226,11 @@ public class RuneWidthGreaterThanOne : Scenario
 
 
     private void UnsetClickedEvent ()
     private void UnsetClickedEvent ()
     {
     {
+        if (_button is null)
+        {
+            return;
+        }
+
         switch (_lastRunesUsed)
         switch (_lastRunesUsed)
         {
         {
             case "Narrow":
             case "Narrow":
@@ -156,10 +248,21 @@ public class RuneWidthGreaterThanOne : Scenario
         }
         }
     }
     }
 
 
-    private void WideMessage (object sender, EventArgs e) { MessageBox.Query ("こんにちはと言う", $"こんにちは {_text.Text}", "Ok"); }
+    private void WideMessage (object? sender, EventArgs e)
+    {
+        if (_text is { })
+        {
+            MessageBox.Query (ApplicationImpl.Instance, "こんにちはと言う", $"こんにちは {_text.Text}", "Ok");
+        }
+    }
 
 
     private void WideRunes ()
     private void WideRunes ()
     {
     {
+        if (_label is null || _text is null || _button is null || _labelR is null || _labelV is null || _win is null)
+        {
+            return;
+        }
+
         UnsetClickedEvent ();
         UnsetClickedEvent ();
         _label.Text = "あなたの名前を入力してください:";
         _label.Text = "あなたの名前を入力してください:";
         _text.Text = "ティラミス";
         _text.Text = "ティラミス";
@@ -175,4 +278,4 @@ public class RuneWidthGreaterThanOne : Scenario
         _lastRunesUsed = "Wide";
         _lastRunesUsed = "Wide";
         Application.LayoutAndDraw ();
         Application.LayoutAndDraw ();
     }
     }
-}
+}

+ 15 - 15
Examples/UICatalog/Scenarios/Scrolling.cs

@@ -16,13 +16,13 @@ public class Scrolling : Scenario
     {
     {
         Application.Init ();
         Application.Init ();
 
 
-        var app = new Window
+        var win = new Window
         {
         {
             Title = GetQuitKeyAndName ()
             Title = GetQuitKeyAndName ()
         };
         };
 
 
         var label = new Label { X = 0, Y = 0 };
         var label = new Label { X = 0, Y = 0 };
-        app.Add (label);
+        win.Add (label);
 
 
         var demoView = new AllViewsView
         var demoView = new AllViewsView
         {
         {
@@ -42,7 +42,7 @@ public class Scrolling : Scenario
                                             $"{demoView}\nContentSize: {demoView.GetContentSize ()}\nViewport.Location: {demoView.Viewport.Location}";
                                             $"{demoView}\nContentSize: {demoView.GetContentSize ()}\nViewport.Location: {demoView.Viewport.Location}";
                                     };
                                     };
 
 
-        app.Add (demoView);
+        win.Add (demoView);
 
 
         var hCheckBox = new CheckBox
         var hCheckBox = new CheckBox
         {
         {
@@ -51,7 +51,7 @@ public class Scrolling : Scenario
             Text = "_HorizontalScrollBar.Visible",
             Text = "_HorizontalScrollBar.Visible",
             CheckedState = demoView.HorizontalScrollBar.Visible ? CheckState.Checked : CheckState.UnChecked
             CheckedState = demoView.HorizontalScrollBar.Visible ? CheckState.Checked : CheckState.UnChecked
         };
         };
-        app.Add (hCheckBox);
+        win.Add (hCheckBox);
         hCheckBox.CheckedStateChanged += (sender, args) => { demoView.HorizontalScrollBar.Visible = args.Value == CheckState.Checked; };
         hCheckBox.CheckedStateChanged += (sender, args) => { demoView.HorizontalScrollBar.Visible = args.Value == CheckState.Checked; };
 
 
         var vCheckBox = new CheckBox
         var vCheckBox = new CheckBox
@@ -61,7 +61,7 @@ public class Scrolling : Scenario
             Text = "_VerticalScrollBar.Visible",
             Text = "_VerticalScrollBar.Visible",
             CheckedState = demoView.VerticalScrollBar.Visible ? CheckState.Checked : CheckState.UnChecked
             CheckedState = demoView.VerticalScrollBar.Visible ? CheckState.Checked : CheckState.UnChecked
         };
         };
-        app.Add (vCheckBox);
+        win.Add (vCheckBox);
         vCheckBox.CheckedStateChanged += (sender, args) => { demoView.VerticalScrollBar.Visible = args.Value == CheckState.Checked; };
         vCheckBox.CheckedStateChanged += (sender, args) => { demoView.VerticalScrollBar.Visible = args.Value == CheckState.Checked; };
 
 
         var ahCheckBox = new CheckBox
         var ahCheckBox = new CheckBox
@@ -77,7 +77,7 @@ public class Scrolling : Scenario
                                                demoView.HorizontalScrollBar.AutoShow = e.Result == CheckState.Checked;
                                                demoView.HorizontalScrollBar.AutoShow = e.Result == CheckState.Checked;
                                                demoView.VerticalScrollBar.AutoShow = e.Result == CheckState.Checked;
                                                demoView.VerticalScrollBar.AutoShow = e.Result == CheckState.Checked;
                                            };
                                            };
-        app.Add (ahCheckBox);
+        win.Add (ahCheckBox);
 
 
         demoView.VerticalScrollBar.VisibleChanging += (sender, args) => { vCheckBox.CheckedState = args.NewValue ? CheckState.Checked : CheckState.UnChecked; };
         demoView.VerticalScrollBar.VisibleChanging += (sender, args) => { vCheckBox.CheckedState = args.NewValue ? CheckState.Checked : CheckState.UnChecked; };
 
 
@@ -92,19 +92,19 @@ public class Scrolling : Scenario
             X = Pos.Center (), Y = Pos.AnchorEnd (), Width = Dim.Fill ()
             X = Pos.Center (), Y = Pos.AnchorEnd (), Width = Dim.Fill ()
         };
         };
 
 
-        app.Add (progress);
+        win.Add (progress);
 
 
-        app.Initialized += AppOnInitialized;
-        app.Unloaded += AppUnloaded;
+        win.Initialized += WinOnInitialized;
+        win.IsRunningChanged += WinIsRunningChanged;
 
 
-        Application.Run (app);
-        app.Unloaded -= AppUnloaded;
-        app.Dispose ();
+        Application.Run (win);
+        win.IsRunningChanged -= WinIsRunningChanged;
+        win.Dispose ();
         Application.Shutdown ();
         Application.Shutdown ();
 
 
         return;
         return;
 
 
-        void AppOnInitialized (object? sender, EventArgs e)
+        void WinOnInitialized (object? sender, EventArgs e)
         {
         {
             bool TimerFn ()
             bool TimerFn ()
             {
             {
@@ -116,9 +116,9 @@ public class Scrolling : Scenario
             _progressTimer = Application.AddTimeout (TimeSpan.FromMilliseconds (200), TimerFn);
             _progressTimer = Application.AddTimeout (TimeSpan.FromMilliseconds (200), TimerFn);
         }
         }
 
 
-        void AppUnloaded (object? sender, EventArgs args)
+        void WinIsRunningChanged (object? sender, EventArgs<bool> args)
         {
         {
-            if (_progressTimer is { })
+            if (!args.Value && _progressTimer is { })
             {
             {
                 Application.RemoveTimeout (_progressTimer);
                 Application.RemoveTimeout (_progressTimer);
                 _progressTimer = null;
                 _progressTimer = null;

+ 31 - 31
Examples/UICatalog/Scenarios/Shortcuts.cs

@@ -15,7 +15,7 @@ public class Shortcuts : Scenario
         var quitKey = Application.QuitKey;
         var quitKey = Application.QuitKey;
         Window app = new ();
         Window app = new ();
 
 
-        app.Loaded += App_Loaded;
+        app.IsModalChanged += App_Loaded;
 
 
         Application.Run (app);
         Application.Run (app);
         app.Dispose ();
         app.Dispose ();
@@ -28,7 +28,7 @@ public class Shortcuts : Scenario
     private void App_Loaded (object? sender, EventArgs e)
     private void App_Loaded (object? sender, EventArgs e)
     {
     {
         Application.QuitKey = Key.F4.WithCtrl;
         Application.QuitKey = Key.F4.WithCtrl;
-        Application.Current!.Title = GetQuitKeyAndName ();
+        Application.TopRunnableView!.Title = GetQuitKeyAndName ();
 
 
         ObservableCollection<string> eventSource = new ();
         ObservableCollection<string> eventSource = new ();
 
 
@@ -38,7 +38,7 @@ public class Shortcuts : Scenario
             X = Pos.AnchorEnd (),
             X = Pos.AnchorEnd (),
             Y = 0,
             Y = 0,
             Height = Dim.Fill (4),
             Height = Dim.Fill (4),
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             Source = new ListWrapper<string> (eventSource),
             Source = new ListWrapper<string> (eventSource),
             BorderStyle = LineStyle.Double,
             BorderStyle = LineStyle.Double,
             Title = "E_vents"
             Title = "E_vents"
@@ -46,14 +46,14 @@ public class Shortcuts : Scenario
 
 
         eventLog.Width = Dim.Func (
         eventLog.Width = Dim.Func (
                                    _ => Math.Min (
                                    _ => Math.Min (
-                                                  Application.Current.Viewport.Width / 2,
+                                                  Application.TopRunnableView.Viewport.Width / 2,
                                                   eventLog?.MaxLength + eventLog!.GetAdornmentsThickness ().Horizontal ?? 0));
                                                   eventLog?.MaxLength + eventLog!.GetAdornmentsThickness ().Horizontal ?? 0));
 
 
         eventLog.Width = Dim.Func (
         eventLog.Width = Dim.Func (
                                    _ => Math.Min (
                                    _ => Math.Min (
                                                   eventLog.SuperView!.Viewport.Width / 2,
                                                   eventLog.SuperView!.Viewport.Width / 2,
                                                   eventLog?.MaxLength + eventLog!.GetAdornmentsThickness ().Horizontal ?? 0));
                                                   eventLog?.MaxLength + eventLog!.GetAdornmentsThickness ().Horizontal ?? 0));
-        Application.Current.Add (eventLog);
+        Application.TopRunnableView.Add (eventLog);
 
 
         var alignKeysShortcut = new Shortcut
         var alignKeysShortcut = new Shortcut
         {
         {
@@ -86,7 +86,7 @@ public class Shortcuts : Scenario
                                                                           };
                                                                           };
 
 
 
 
-        Application.Current.Add (alignKeysShortcut);
+        Application.TopRunnableView.Add (alignKeysShortcut);
 
 
         var commandFirstShortcut = new Shortcut
         var commandFirstShortcut = new Shortcut
         {
         {
@@ -115,7 +115,7 @@ public class Shortcuts : Scenario
                                                                                                       $"{commandFirstShortcut.Id}.CommandView.CheckedStateChanging: {cb.Text}");
                                                                                                       $"{commandFirstShortcut.Id}.CommandView.CheckedStateChanging: {cb.Text}");
                                                                                      eventLog.MoveDown ();
                                                                                      eventLog.MoveDown ();
 
 
-                                                                                     IEnumerable<View> toAlign = Application.Current.SubViews.OfType<Shortcut> ();
+                                                                                     IEnumerable<View> toAlign = Application.TopRunnableView.SubViews.OfType<Shortcut> ();
                                                                                      IEnumerable<View> enumerable = toAlign as View [] ?? toAlign.ToArray ();
                                                                                      IEnumerable<View> enumerable = toAlign as View [] ?? toAlign.ToArray ();
 
 
                                                                                      foreach (View view in enumerable)
                                                                                      foreach (View view in enumerable)
@@ -134,7 +134,7 @@ public class Shortcuts : Scenario
                                                                                  }
                                                                                  }
                                                                              };
                                                                              };
 
 
-        Application.Current.Add (commandFirstShortcut);
+        Application.TopRunnableView.Add (commandFirstShortcut);
 
 
         var canFocusShortcut = new Shortcut
         var canFocusShortcut = new Shortcut
         {
         {
@@ -159,7 +159,7 @@ public class Shortcuts : Scenario
                                                                                  SetCanFocus (e.Result == CheckState.Checked);
                                                                                  SetCanFocus (e.Result == CheckState.Checked);
                                                                              }
                                                                              }
                                                                          };
                                                                          };
-        Application.Current.Add (canFocusShortcut);
+        Application.TopRunnableView.Add (canFocusShortcut);
 
 
         var appShortcut = new Shortcut
         var appShortcut = new Shortcut
         {
         {
@@ -173,7 +173,7 @@ public class Shortcuts : Scenario
             BindKeyToApplication = true
             BindKeyToApplication = true
         };
         };
 
 
-        Application.Current.Add (appShortcut);
+        Application.TopRunnableView.Add (appShortcut);
 
 
         var buttonShortcut = new Shortcut
         var buttonShortcut = new Shortcut
         {
         {
@@ -193,7 +193,7 @@ public class Shortcuts : Scenario
         var button = (Button)buttonShortcut.CommandView;
         var button = (Button)buttonShortcut.CommandView;
         buttonShortcut.Accepting += Button_Clicked;
         buttonShortcut.Accepting += Button_Clicked;
 
 
-        Application.Current.Add (buttonShortcut);
+        Application.TopRunnableView.Add (buttonShortcut);
 
 
         var optionSelectorShortcut = new Shortcut
         var optionSelectorShortcut = new Shortcut
         {
         {
@@ -221,7 +221,7 @@ public class Shortcuts : Scenario
                                                                                     }
                                                                                     }
                                                                                 };
                                                                                 };
 
 
-        Application.Current.Add (optionSelectorShortcut);
+        Application.TopRunnableView.Add (optionSelectorShortcut);
 
 
         var sliderShortcut = new Shortcut
         var sliderShortcut = new Shortcut
         {
         {
@@ -248,7 +248,7 @@ public class Shortcuts : Scenario
                                                                            eventLog.MoveDown ();
                                                                            eventLog.MoveDown ();
                                                                        };
                                                                        };
 
 
-        Application.Current.Add (sliderShortcut);
+        Application.TopRunnableView.Add (sliderShortcut);
 
 
         ListView listView = new ListView ()
         ListView listView = new ListView ()
         {
         {
@@ -270,7 +270,7 @@ public class Shortcuts : Scenario
             Key = Key.F5.WithCtrl,
             Key = Key.F5.WithCtrl,
         };
         };
 
 
-        Application.Current.Add (listViewShortcut);
+        Application.TopRunnableView.Add (listViewShortcut);
 
 
         var noCommandShortcut = new Shortcut
         var noCommandShortcut = new Shortcut
         {
         {
@@ -282,7 +282,7 @@ public class Shortcuts : Scenario
             Key = Key.D0
             Key = Key.D0
         };
         };
 
 
-        Application.Current.Add (noCommandShortcut);
+        Application.TopRunnableView.Add (noCommandShortcut);
 
 
         var noKeyShortcut = new Shortcut
         var noKeyShortcut = new Shortcut
         {
         {
@@ -295,7 +295,7 @@ public class Shortcuts : Scenario
             HelpText = "Keyless"
             HelpText = "Keyless"
         };
         };
 
 
-        Application.Current.Add (noKeyShortcut);
+        Application.TopRunnableView.Add (noKeyShortcut);
 
 
         var noHelpShortcut = new Shortcut
         var noHelpShortcut = new Shortcut
         {
         {
@@ -308,7 +308,7 @@ public class Shortcuts : Scenario
             HelpText = ""
             HelpText = ""
         };
         };
 
 
-        Application.Current.Add (noHelpShortcut);
+        Application.TopRunnableView.Add (noHelpShortcut);
         noHelpShortcut.SetFocus ();
         noHelpShortcut.SetFocus ();
 
 
         var framedShortcut = new Shortcut
         var framedShortcut = new Shortcut
@@ -339,8 +339,8 @@ public class Shortcuts : Scenario
             framedShortcut.KeyView.SchemeName = framedShortcut.KeyView.SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Base);
             framedShortcut.KeyView.SchemeName = framedShortcut.KeyView.SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Base);
         }
         }
 
 
-        framedShortcut.SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Toplevel);
-        Application.Current.Add (framedShortcut);
+        framedShortcut.SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Runnable);
+        Application.TopRunnableView.Add (framedShortcut);
 
 
         // Horizontal
         // Horizontal
         var progressShortcut = new Shortcut
         var progressShortcut = new Shortcut
@@ -387,7 +387,7 @@ public class Shortcuts : Scenario
                          };
                          };
         timer.Start ();
         timer.Start ();
 
 
-        Application.Current.Add (progressShortcut);
+        Application.TopRunnableView.Add (progressShortcut);
 
 
         var textField = new TextField
         var textField = new TextField
         {
         {
@@ -408,7 +408,7 @@ public class Shortcuts : Scenario
         };
         };
         textField.CanFocus = true;
         textField.CanFocus = true;
 
 
-        Application.Current.Add (textFieldShortcut);
+        Application.TopRunnableView.Add (textFieldShortcut);
 
 
         var bgColorShortcut = new Shortcut
         var bgColorShortcut = new Shortcut
         {
         {
@@ -450,19 +450,19 @@ public class Shortcuts : Scenario
                                         eventSource.Add ($"ColorChanged: {o.GetType ().Name} - {args.Result}");
                                         eventSource.Add ($"ColorChanged: {o.GetType ().Name} - {args.Result}");
                                         eventLog.MoveDown ();
                                         eventLog.MoveDown ();
 
 
-                                        Application.Current.SetScheme (
-                                                                   new (Application.Current.GetScheme ())
+                                        Application.TopRunnableView.SetScheme (
+                                                                   new (Application.TopRunnableView.GetScheme ())
                                                                    {
                                                                    {
                                                                        Normal = new (
                                                                        Normal = new (
-                                                                                     Application.Current!.GetAttributeForRole (VisualRole.Normal).Foreground,
+                                                                                     Application.TopRunnableView!.GetAttributeForRole (VisualRole.Normal).Foreground,
                                                                                      args.Result,
                                                                                      args.Result,
-                                                                                     Application.Current!.GetAttributeForRole (VisualRole.Normal).Style)
+                                                                                     Application.TopRunnableView!.GetAttributeForRole (VisualRole.Normal).Style)
                                                                    });
                                                                    });
                                     }
                                     }
                                 };
                                 };
         bgColorShortcut.CommandView = bgColor;
         bgColorShortcut.CommandView = bgColor;
 
 
-        Application.Current.Add (bgColorShortcut);
+        Application.TopRunnableView.Add (bgColorShortcut);
 
 
         var appQuitShortcut = new Shortcut
         var appQuitShortcut = new Shortcut
         {
         {
@@ -476,9 +476,9 @@ public class Shortcuts : Scenario
         };
         };
         appQuitShortcut.Accepting += (o, args) => { Application.RequestStop (); };
         appQuitShortcut.Accepting += (o, args) => { Application.RequestStop (); };
 
 
-        Application.Current.Add (appQuitShortcut);
+        Application.TopRunnableView.Add (appQuitShortcut);
 
 
-        foreach (Shortcut shortcut in Application.Current.SubViews.OfType<Shortcut> ())
+        foreach (Shortcut shortcut in Application.TopRunnableView.SubViews.OfType<Shortcut> ())
         {
         {
             shortcut.Selecting += (o, args) =>
             shortcut.Selecting += (o, args) =>
                                   {
                                   {
@@ -529,7 +529,7 @@ public class Shortcuts : Scenario
 
 
         void SetCanFocus (bool canFocus)
         void SetCanFocus (bool canFocus)
         {
         {
-            foreach (Shortcut peer in Application.Current!.SubViews.OfType<Shortcut> ())
+            foreach (Shortcut peer in Application.TopRunnableView!.SubViews.OfType<Shortcut> ())
             {
             {
                 if (peer.CanFocus)
                 if (peer.CanFocus)
                 {
                 {
@@ -542,7 +542,7 @@ public class Shortcuts : Scenario
         {
         {
             var max = 0;
             var max = 0;
 
 
-            IEnumerable<Shortcut> toAlign = Application.Current!.SubViews.OfType<Shortcut> ().Where(s => !s.Y.Has<PosAnchorEnd>(out _)).Cast<Shortcut>();
+            IEnumerable<Shortcut> toAlign = Application.TopRunnableView!.SubViews.OfType<Shortcut> ().Where(s => !s.Y.Has<PosAnchorEnd>(out _)).Cast<Shortcut>();
             IEnumerable<Shortcut> enumerable = toAlign as Shortcut [] ?? toAlign.ToArray ();
             IEnumerable<Shortcut> enumerable = toAlign as Shortcut [] ?? toAlign.ToArray ();
 
 
             if (align)
             if (align)
@@ -566,6 +566,6 @@ public class Shortcuts : Scenario
     {
     {
         e.Handled = true;
         e.Handled = true;
         var view = sender as View;
         var view = sender as View;
-        MessageBox.Query ("Hi", $"You clicked {view?.Text}", "_Ok");
+        MessageBox.Query ((sender as View)?.App, "Hi", $"You clicked {view?.Text}", "_Ok");
     }
     }
 }
 }

+ 126 - 117
Examples/UICatalog/Scenarios/SingleBackgroundWorker.cs

@@ -1,12 +1,11 @@
-using System;
-using System.Collections.Generic;
+#nullable enable
+
 using System.Collections.ObjectModel;
 using System.Collections.ObjectModel;
 using System.ComponentModel;
 using System.ComponentModel;
-using System.Threading;
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
 
 
-[ScenarioMetadata ("Single BackgroundWorker", "A single BackgroundWorker threading opening another Toplevel")]
+[ScenarioMetadata ("Single BackgroundWorker", "A single BackgroundWorker threading opening another Runnable")]
 [ScenarioCategory ("Threading")]
 [ScenarioCategory ("Threading")]
 [ScenarioCategory ("Arrangement")]
 [ScenarioCategory ("Arrangement")]
 [ScenarioCategory ("Runnable")]
 [ScenarioCategory ("Runnable")]
@@ -14,58 +13,56 @@ public class SingleBackgroundWorker : Scenario
 {
 {
     public override void Main ()
     public override void Main ()
     {
     {
-        Application.Run<MainApp> ().Dispose ();
+        Application.Run<MainApp> ();
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
-    public class MainApp : Toplevel
+    public class MainApp : Window
     {
     {
         private readonly ListView _listLog;
         private readonly ListView _listLog;
         private readonly ObservableCollection<string> _log = [];
         private readonly ObservableCollection<string> _log = [];
         private DateTime? _startStaging;
         private DateTime? _startStaging;
-        private BackgroundWorker _worker;
+        private BackgroundWorker? _worker;
 
 
         public MainApp ()
         public MainApp ()
         {
         {
-            var menu = new MenuBar
-            {
-                Menus =
-                [
-                    new (
-                         "_Options",
-                         new MenuItem []
-                         {
-                             new (
-                                  "_Run Worker",
-                                  "",
-                                  () => RunWorker (),
-                                  null,
-                                  null,
-                                  KeyCode.CtrlMask | KeyCode.R
-                                 ),
-                             null,
-                             new (
-                                  "_Quit",
-                                  "",
-                                  () => Application.RequestStop (),
-                                  null,
-                                  null,
-                                  Application.QuitKey
-                                 )
-                         }
-                        )
-                ]
-            };
-
-            var statusBar = new StatusBar (
-                                           [
-                                               new (Application.QuitKey, "Quit", () => Application.RequestStop ()),
-                                               new (Key.R.WithCtrl, "Run Worker", RunWorker)
-                                           ]);
-
-            var workerLogTop = new Toplevel
+            BorderStyle = LineStyle.None;
+            // MenuBar
+            MenuBar menu = new ();
+
+            menu.Add (
+                      new MenuBarItem (
+                                       "_Options",
+                                       [
+                                           new MenuItem
+                                           {
+                                               Title = "_Run Worker",
+                                               Key = Key.R.WithCtrl,
+                                               Action = RunWorker
+                                           },
+                                           new MenuItem
+                                           {
+                                               Title = "_Quit",
+                                               Key = Application.QuitKey,
+                                               Action = () => Application.RequestStop ()
+                                           }
+                                       ]
+                                      )
+                     );
+
+            // StatusBar
+            StatusBar statusBar = new (
+                                       [
+                                           new (Application.QuitKey, "Quit", () => Application.RequestStop ()),
+                                           new (Key.R.WithCtrl, "Run Worker", RunWorker)
+                                       ]
+                                      );
+
+            Window workerLogTop = new ()
             {
             {
-                Title = "Worker Log Top"
+                Title = "Worker Log Top",
+                Y = Pos.Bottom (menu),
+                Height = Dim.Fill (1)
             };
             };
 
 
             workerLogTop.Add (
             workerLogTop.Add (
@@ -82,9 +79,6 @@ public class SingleBackgroundWorker : Scenario
             };
             };
             workerLogTop.Add (_listLog);
             workerLogTop.Add (_listLog);
 
 
-            workerLogTop.Y = 1;
-            workerLogTop.Height = Dim.Fill (Dim.Func (_ => statusBar.Frame.Height));
-
             Add (menu, workerLogTop, statusBar);
             Add (menu, workerLogTop, statusBar);
             Title = "MainApp";
             Title = "MainApp";
         }
         }
@@ -93,11 +87,11 @@ public class SingleBackgroundWorker : Scenario
         {
         {
             _worker = new () { WorkerSupportsCancellation = true };
             _worker = new () { WorkerSupportsCancellation = true };
 
 
-            var cancel = new Button { Text = "Cancel Worker" };
+            Button cancel = new () { Text = "Cancel Worker" };
 
 
             cancel.Accepting += (s, e) =>
             cancel.Accepting += (s, e) =>
                                 {
                                 {
-                                    if (_worker == null)
+                                    if (_worker is null)
                                     {
                                     {
                                         _log.Add ($"Worker is not running at {DateTime.Now}!");
                                         _log.Add ($"Worker is not running at {DateTime.Now}!");
                                         _listLog.SetNeedsDraw ();
                                         _listLog.SetNeedsDraw ();
@@ -116,9 +110,10 @@ public class SingleBackgroundWorker : Scenario
             _log.Add ($"Worker is started at {_startStaging}.{_startStaging:fff}");
             _log.Add ($"Worker is started at {_startStaging}.{_startStaging:fff}");
             _listLog.SetNeedsDraw ();
             _listLog.SetNeedsDraw ();
 
 
-            var md = new Dialog
+            Dialog md = new ()
             {
             {
-                Title = $"Running Worker started at {_startStaging}.{_startStaging:fff}", Buttons = [cancel]
+                Title = $"Running Worker started at {_startStaging}.{_startStaging:fff}",
+                Buttons = [cancel]
             };
             };
 
 
             md.Add (
             md.Add (
@@ -127,7 +122,7 @@ public class SingleBackgroundWorker : Scenario
 
 
             _worker.DoWork += (s, e) =>
             _worker.DoWork += (s, e) =>
                               {
                               {
-                                  List<string> stageResult = new ();
+                                  List<string> stageResult = [];
 
 
                                   for (var i = 0; i < 200; i++)
                                   for (var i = 0; i < 200; i++)
                                   {
                                   {
@@ -135,7 +130,7 @@ public class SingleBackgroundWorker : Scenario
                                       e.Result = stageResult;
                                       e.Result = stageResult;
                                       Thread.Sleep (1);
                                       Thread.Sleep (1);
 
 
-                                      if (_worker.CancellationPending)
+                                      if (_worker?.CancellationPending == true)
                                       {
                                       {
                                           e.Cancel = true;
                                           e.Cancel = true;
 
 
@@ -152,7 +147,7 @@ public class SingleBackgroundWorker : Scenario
                                                   Application.RequestStop ();
                                                   Application.RequestStop ();
                                               }
                                               }
 
 
-                                              if (e.Error != null)
+                                              if (e.Error is { })
                                               {
                                               {
                                                   // Failed
                                                   // Failed
                                                   _log.Add (
                                                   _log.Add (
@@ -177,14 +172,22 @@ public class SingleBackgroundWorker : Scenario
                                                   _listLog.SetNeedsDraw ();
                                                   _listLog.SetNeedsDraw ();
                                                   Application.LayoutAndDraw ();
                                                   Application.LayoutAndDraw ();
 
 
-                                                  var builderUI =
-                                                      new StagingUIController (_startStaging, e.Result as ObservableCollection<string>);
-                                                  Toplevel top = Application.Current;
-                                                  top.Visible = false;
-                                                  Application.Current.Visible = false;
+                                                  StagingUIController builderUI =
+                                                      new (_startStaging, e.Result as ObservableCollection<string>);
+                                                  View? top = Application.TopRunnableView;
+
+                                                  if (top is { })
+                                                  {
+                                                      top.Visible = false;
+                                                  }
+
                                                   builderUI.Load ();
                                                   builderUI.Load ();
                                                   builderUI.Dispose ();
                                                   builderUI.Dispose ();
-                                                  top.Visible = true;
+
+                                                  if (top is { })
+                                                  {
+                                                      top.Visible = true;
+                                                  }
                                               }
                                               }
 
 
                                               _worker = null;
                                               _worker = null;
@@ -197,13 +200,15 @@ public class SingleBackgroundWorker : Scenario
 
 
     public class StagingUIController : Window
     public class StagingUIController : Window
     {
     {
-        private Toplevel _top;
+        private Runnable? _top;
 
 
-        public StagingUIController (DateTime? start, ObservableCollection<string> list)
+        public StagingUIController (DateTime? start, ObservableCollection<string>? list)
         {
         {
             _top = new ()
             _top = new ()
             {
             {
-                Title = "_top", Width = Dim.Fill (), Height = Dim.Fill (), Modal = true
+                Title = "_top",
+                Width = Dim.Fill (),
+                Height = Dim.Fill (),
             };
             };
 
 
             _top.KeyDown += (s, e) =>
             _top.KeyDown += (s, e) =>
@@ -218,7 +223,7 @@ public class SingleBackgroundWorker : Scenario
 
 
             bool Close ()
             bool Close ()
             {
             {
-                int n = MessageBox.Query (
+                int? n = MessageBox.Query (App,
                                           50,
                                           50,
                                           7,
                                           7,
                                           "Close Window.",
                                           "Close Window.",
@@ -230,74 +235,78 @@ public class SingleBackgroundWorker : Scenario
                 return n == 0;
                 return n == 0;
             }
             }
 
 
-            var menu = new MenuBar
-            {
-                Menus =
-                [
-                    new (
-                         "_Stage",
-                         new MenuItem []
-                         {
-                             new (
-                                  "_Close",
-                                  "",
-                                  () =>
-                                  {
-                                      if (Close ())
-                                      {
-                                          Application.RequestStop ();
-                                      }
-                                  },
-                                  null,
-                                  null,
-                                  KeyCode.CtrlMask | KeyCode.C
-                                 )
-                         }
-                        )
-                ]
-            };
+            // MenuBar
+            MenuBar menu = new ();
+
+            menu.Add (
+                      new MenuBarItem (
+                                       "_Stage",
+                                       [
+                                           new MenuItem
+                                           {
+                                               Title = "_Close",
+                                               Key = Key.C.WithCtrl,
+                                               Action = () =>
+                                                        {
+                                                            if (Close ())
+                                                            {
+                                                                App?.RequestStop ();
+                                                            }
+                                                        }
+                                           }
+                                       ]
+                                      )
+                     );
             _top.Add (menu);
             _top.Add (menu);
 
 
-            var statusBar = new StatusBar (
-                                           [
-                                               new (
-                                                    Key.C.WithCtrl,
-                                                    "Close",
-                                                    () =>
+            // StatusBar
+            StatusBar statusBar = new (
+                                       [
+                                           new (
+                                                Key.C.WithCtrl,
+                                                "Close",
+                                                () =>
+                                                {
+                                                    if (Close ())
                                                     {
                                                     {
-                                                        if (Close ())
-                                                        {
-                                                            Application.RequestStop ();
-                                                        }
+                                                        App?.RequestStop ();
                                                     }
                                                     }
-                                                   )
-                                           ]);
+                                                }
+                                               )
+                                       ]
+                                      );
             _top.Add (statusBar);
             _top.Add (statusBar);
 
 
-            Y = 1;
+            Y = Pos.Bottom (menu);
             Height = Dim.Fill (1);
             Height = Dim.Fill (1);
             Title = $"Worker started at {start}.{start:fff}";
             Title = $"Worker started at {start}.{start:fff}";
             SchemeName = "Base";
             SchemeName = "Base";
 
 
-            Add (
-                 new ListView
-                 {
-                     X = 0,
-                     Y = 0,
-                     Width = Dim.Fill (),
-                     Height = Dim.Fill (),
-                     Source = new ListWrapper<string> (list)
-                 }
-                );
+            if (list is { })
+            {
+                Add (
+                     new ListView
+                     {
+                         X = 0,
+                         Y = 0,
+                         Width = Dim.Fill (),
+                         Height = Dim.Fill (),
+                         Source = new ListWrapper<string> (list)
+                     }
+                    );
+            }
 
 
             _top.Add (this);
             _top.Add (this);
         }
         }
 
 
         public void Load ()
         public void Load ()
         {
         {
-            Application.Run (_top);
-            _top.Dispose ();
-            _top = null;
+            if (_top is { })
+            {
+                App?.Run (_top);
+                _top.Dispose ();
+                _top = null;
+            }
         }
         }
     }
     }
 }
 }

+ 9 - 9
Examples/UICatalog/Scenarios/Sliders.cs

@@ -86,17 +86,17 @@ public class Sliders : Scenario
                                 {
                                 {
                                     if (single.Orientation == Orientation.Horizontal)
                                     if (single.Orientation == Orientation.Horizontal)
                                     {
                                     {
-                                        single.Style.SpaceChar = new () { Rune = Glyphs.HLine };
-                                        single.Style.OptionChar = new () { Rune = Glyphs.HLine };
+                                        single.Style.SpaceChar = new () { Grapheme = Glyphs.HLine.ToString () };
+                                        single.Style.OptionChar = new () { Grapheme = Glyphs.HLine.ToString () };
                                     }
                                     }
                                     else
                                     else
                                     {
                                     {
-                                        single.Style.SpaceChar = new () { Rune = Glyphs.VLine };
-                                        single.Style.OptionChar = new () { Rune = Glyphs.VLine };
+                                        single.Style.SpaceChar = new () { Grapheme = Glyphs.VLine.ToString () };
+                                        single.Style.OptionChar = new () { Grapheme = Glyphs.VLine.ToString () };
                                     }
                                     }
                                 };
                                 };
-        single.Style.SetChar = new () { Rune = Glyphs.ContinuousMeterSegment };
-        single.Style.DragChar = new () { Rune = Glyphs.ContinuousMeterSegment };
+        single.Style.SetChar = new () { Grapheme = Glyphs.ContinuousMeterSegment.ToString () };
+        single.Style.DragChar = new () { Grapheme = Glyphs.ContinuousMeterSegment.ToString () };
 
 
         v.Add (single);
         v.Add (single);
 
 
@@ -257,7 +257,7 @@ public class Sliders : Scenario
                                                     {
                                                     {
                                                         s.Orientation = Orientation.Horizontal;
                                                         s.Orientation = Orientation.Horizontal;
 
 
-                                                        s.Style.SpaceChar = new () { Rune = Glyphs.HLine };
+                                                        s.Style.SpaceChar = new () { Grapheme = Glyphs.HLine.ToString () };
 
 
                                                         if (prev == null)
                                                         if (prev == null)
                                                         {
                                                         {
@@ -275,7 +275,7 @@ public class Sliders : Scenario
                                                     {
                                                     {
                                                         s.Orientation = Orientation.Vertical;
                                                         s.Orientation = Orientation.Vertical;
 
 
-                                                        s.Style.SpaceChar = new () { Rune = Glyphs.VLine };
+                                                        s.Style.SpaceChar = new () { Grapheme = Glyphs.VLine.ToString () };
 
 
                                                         if (prev == null)
                                                         if (prev == null)
                                                         {
                                                         {
@@ -590,7 +590,7 @@ public class Sliders : Scenario
             Y = Pos.Bottom (spacingOptions),
             Y = Pos.Bottom (spacingOptions),
             Width = Dim.Fill (),
             Width = Dim.Fill (),
             Height = Dim.Fill (),
             Height = Dim.Fill (),
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             Source = new ListWrapper<string> (eventSource)
             Source = new ListWrapper<string> (eventSource)
         };
         };
         configView.Add (eventLog);
         configView.Add (eventLog);

+ 17 - 17
Examples/UICatalog/Scenarios/SpinnerStyles.cs

@@ -14,7 +14,7 @@ public class SpinnerViewStyles : Scenario
     {
     {
         Application.Init ();
         Application.Init ();
 
 
-        Window app = new ()
+        Window win = new ()
         {
         {
             Title = GetQuitKeyAndName ()
             Title = GetQuitKeyAndName ()
         };
         };
@@ -40,7 +40,7 @@ public class SpinnerViewStyles : Scenario
             //Title = "Preview",
             //Title = "Preview",
             BorderStyle = LineStyle.Single
             BorderStyle = LineStyle.Single
         };
         };
-        app.Add (preview);
+        win.Add (preview);
 
 
         var spinner = new SpinnerView { X = Pos.Center (), Y = 0 };
         var spinner = new SpinnerView { X = Pos.Center (), Y = 0 };
         preview.Add (spinner);
         preview.Add (spinner);
@@ -54,7 +54,7 @@ public class SpinnerViewStyles : Scenario
             CheckedState = CheckState.Checked,
             CheckedState = CheckState.Checked,
             Text = "Ascii Only"
             Text = "Ascii Only"
         };
         };
-        app.Add (ckbAscii);
+        win.Add (ckbAscii);
 
 
         var ckbNoSpecial = new CheckBox
         var ckbNoSpecial = new CheckBox
         {
         {
@@ -64,28 +64,28 @@ public class SpinnerViewStyles : Scenario
             CheckedState = CheckState.Checked,
             CheckedState = CheckState.Checked,
             Text = "No Special"
             Text = "No Special"
         };
         };
-        app.Add (ckbNoSpecial);
+        win.Add (ckbNoSpecial);
 
 
         var ckbReverse = new CheckBox
         var ckbReverse = new CheckBox
         {
         {
             X = Pos.Center () - 22, Y = Pos.Bottom (preview) + 1, CheckedState = CheckState.UnChecked, Text = "Reverse"
             X = Pos.Center () - 22, Y = Pos.Bottom (preview) + 1, CheckedState = CheckState.UnChecked, Text = "Reverse"
         };
         };
-        app.Add (ckbReverse);
+        win.Add (ckbReverse);
 
 
         var ckbBounce = new CheckBox
         var ckbBounce = new CheckBox
         {
         {
             X = Pos.Right (ckbReverse) + 2, Y = Pos.Bottom (preview) + 1, CheckedState = CheckState.UnChecked, Text = "Bounce"
             X = Pos.Right (ckbReverse) + 2, Y = Pos.Bottom (preview) + 1, CheckedState = CheckState.UnChecked, Text = "Bounce"
         };
         };
-        app.Add (ckbBounce);
+        win.Add (ckbBounce);
 
 
         var delayLabel = new Label { X = Pos.Right (ckbBounce) + 2, Y = Pos.Bottom (preview) + 1, Text = "Delay:" };
         var delayLabel = new Label { X = Pos.Right (ckbBounce) + 2, Y = Pos.Bottom (preview) + 1, Text = "Delay:" };
-        app.Add (delayLabel);
+        win.Add (delayLabel);
 
 
         var delayField = new TextField
         var delayField = new TextField
         {
         {
             X = Pos.Right (delayLabel), Y = Pos.Bottom (preview) + 1, Width = 5, Text = DEFAULT_DELAY.ToString ()
             X = Pos.Right (delayLabel), Y = Pos.Bottom (preview) + 1, Width = 5, Text = DEFAULT_DELAY.ToString ()
         };
         };
-        app.Add (delayField);
+        win.Add (delayField);
 
 
         delayField.TextChanged += (s, e) =>
         delayField.TextChanged += (s, e) =>
                                   {
                                   {
@@ -96,13 +96,13 @@ public class SpinnerViewStyles : Scenario
                                   };
                                   };
 
 
         var customLabel = new Label { X = Pos.Right (delayField) + 2, Y = Pos.Bottom (preview) + 1, Text = "Custom:" };
         var customLabel = new Label { X = Pos.Right (delayField) + 2, Y = Pos.Bottom (preview) + 1, Text = "Custom:" };
-        app.Add (customLabel);
+        win.Add (customLabel);
 
 
         var customField = new TextField
         var customField = new TextField
         {
         {
             X = Pos.Right (customLabel), Y = Pos.Bottom (preview) + 1, Width = 12, Text = DEFAULT_CUSTOM
             X = Pos.Right (customLabel), Y = Pos.Bottom (preview) + 1, Width = 12, Text = DEFAULT_CUSTOM
         };
         };
-        app.Add (customField);
+        win.Add (customField);
 
 
         string [] styleArray = styleDict.Select (e => e.Value.Key).ToArray ();
         string [] styleArray = styleDict.Select (e => e.Value.Key).ToArray ();
 
 
@@ -117,7 +117,7 @@ public class SpinnerViewStyles : Scenario
         };
         };
         styles.SetSource (new ObservableCollection<string> (styleArray));
         styles.SetSource (new ObservableCollection<string> (styleArray));
         styles.SelectedItem = 0; // SpinnerStyle.Custom;
         styles.SelectedItem = 0; // SpinnerStyle.Custom;
-        app.Add (styles);
+        win.Add (styles);
         SetCustom ();
         SetCustom ();
 
 
         customField.TextChanged += (s, e) =>
         customField.TextChanged += (s, e) =>
@@ -166,7 +166,7 @@ public class SpinnerViewStyles : Scenario
 
 
         ckbBounce.CheckedStateChanging += (s, e) => { spinner.SpinBounce = e.Result == CheckState.Checked; };
         ckbBounce.CheckedStateChanging += (s, e) => { spinner.SpinBounce = e.Result == CheckState.Checked; };
 
 
-        app.Unloaded += App_Unloaded;
+        win.IsRunningChanged += WinIsRunningChanged;
 
 
         void SetCustom ()
         void SetCustom ()
         {
         {
@@ -199,23 +199,23 @@ public class SpinnerViewStyles : Scenario
             }
             }
         }
         }
 
 
-        void App_Unloaded (object sender, EventArgs args)
+        void WinIsRunningChanged (object sender, EventArgs<bool> args)
         {
         {
-            if (spinner is {})
+            if (!args.Value && spinner is {})
             {
             {
                 spinner.Dispose ();
                 spinner.Dispose ();
                 spinner = null;
                 spinner = null;
             }
             }
         }
         }
 
 
-        Application.Run (app);
-        app.Unloaded -= App_Unloaded;
+        Application.Run (win);
+        win.IsRunningChanged -= WinIsRunningChanged;
         if (spinner is { })
         if (spinner is { })
         {
         {
             spinner.Dispose ();
             spinner.Dispose ();
             spinner = null;
             spinner = null;
         }
         }
-        app.Dispose ();
+        win.Dispose ();
 
 
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }

+ 58 - 65
Examples/UICatalog/Scenarios/SyntaxHighlighting.cs

@@ -1,8 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.IO;
-using System.Linq;
+using System.ComponentModel;
 using System.Reflection;
 using System.Reflection;
 using System.Text;
 using System.Text;
 using System.Text.Json;
 using System.Text.Json;
@@ -88,7 +84,6 @@ public class SyntaxHighlighting : Scenario
     private Attribute _blue;
     private Attribute _blue;
     private Attribute _green;
     private Attribute _green;
     private Attribute _magenta;
     private Attribute _magenta;
-    private MenuItem _miWrap;
     private TextView _textView;
     private TextView _textView;
     private Attribute _white;
     private Attribute _white;
 
 
@@ -99,7 +94,7 @@ public class SyntaxHighlighting : Scenario
     /// <typeparam name="T">The type of object to read from the file.</typeparam>
     /// <typeparam name="T">The type of object to read from the file.</typeparam>
     /// <param name="filePath">The file path to read the object instance from.</param>
     /// <param name="filePath">The file path to read the object instance from.</param>
     /// <returns>Returns a new instance of the object read from the Json file.</returns>
     /// <returns>Returns a new instance of the object read from the Json file.</returns>
-    public static T ReadFromJsonFile<T> (string filePath) where T : new()
+    public static T ReadFromJsonFile<T> (string filePath) where T : new ()
     {
     {
         TextReader reader = null;
         TextReader reader = null;
 
 
@@ -125,48 +120,28 @@ public class SyntaxHighlighting : Scenario
         Application.Init ();
         Application.Init ();
 
 
         // Setup - Create a top-level application window and configure it.
         // Setup - Create a top-level application window and configure it.
-        Toplevel appWindow = new ();
+        Runnable appWindow = new ();
+
+        var menu = new MenuBar ();
+
+        MenuItem wrapMenuItem = CreateWordWrapMenuItem ();
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_TextView",
+                                   [
+                                       wrapMenuItem,
+                                       new Line (),
+                                       new MenuItem { Title = "_Syntax Highlighting", Action = ApplySyntaxHighlighting },
+                                       new Line (),
+                                       new MenuItem { Title = "_Load Text Cells", Action = ApplyLoadCells },
+                                       new MenuItem { Title = "_Save Text Cells", Action = SaveCells },
+                                       new Line (),
+                                       new MenuItem { Title = "_Quit", Action = Quit }
+                                   ]
+                                  )
+                 );
 
 
-        var menu = new MenuBar
-        {
-            Menus =
-            [
-                new (
-                     "_TextView",
-                     new []
-                     {
-                         _miWrap = new (
-                                        "_Word Wrap",
-                                        "",
-                                        () => WordWrap ()
-                                       )
-                         {
-                             CheckType = MenuItemCheckStyle
-                                 .Checked
-                         },
-                         null,
-                         new (
-                              "_Syntax Highlighting",
-                              "",
-                              () => ApplySyntaxHighlighting ()
-                             ),
-                         null,
-                         new (
-                              "_Load Rune Cells",
-                              "",
-                              () => ApplyLoadCells ()
-                             ),
-                         new (
-                              "_Save Rune Cells",
-                              "",
-                              () => SaveCells ()
-                             ),
-                         null,
-                         new ("_Quit", "", () => Quit ())
-                     }
-                    )
-            ]
-        };
         appWindow.Add (menu);
         appWindow.Add (menu);
 
 
         _textView = new ()
         _textView = new ()
@@ -192,6 +167,33 @@ public class SyntaxHighlighting : Scenario
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
+    private MenuItem CreateWordWrapMenuItem ()
+    {
+        CheckBox checkBox = new ()
+        {
+            Title = "_Word Wrap",
+            CheckedState = _textView?.WordWrap == true ? CheckState.Checked : CheckState.UnChecked
+        };
+
+        checkBox.CheckedStateChanged += (s, e) =>
+                                        {
+                                            if (_textView is { })
+                                            {
+                                                _textView.WordWrap = checkBox.CheckedState == CheckState.Checked;
+                                            }
+                                        };
+
+        MenuItem item = new () { CommandView = checkBox };
+
+        item.Accepting += (s, e) =>
+                          {
+                              checkBox.AdvanceCheckState ();
+                              e.Handled = true;
+                          };
+
+        return item;
+    }
+
     /// <summary>
     /// <summary>
     ///     Writes the given object instance to a Json file.
     ///     Writes the given object instance to a Json file.
     ///     <para>Object type must have a parameterless constructor.</para>
     ///     <para>Object type must have a parameterless constructor.</para>
@@ -211,7 +213,7 @@ public class SyntaxHighlighting : Scenario
     ///     If false the file will be overwritten if it already exists. If true the contents will be appended
     ///     If false the file will be overwritten if it already exists. If true the contents will be appended
     ///     to the file.
     ///     to the file.
     /// </param>
     /// </param>
-    public static void WriteToJsonFile<T> (string filePath, T objectToWrite, bool append = false) where T : new()
+    public static void WriteToJsonFile<T> (string filePath, T objectToWrite, bool append = false) where T : new ()
     {
     {
         TextWriter writer = null;
         TextWriter writer = null;
 
 
@@ -240,12 +242,9 @@ public class SyntaxHighlighting : Scenario
         {
         {
             string csName = color.Key;
             string csName = color.Key;
 
 
-            foreach (Rune rune in csName.EnumerateRunes ())
-            {
-                cells.Add (new () { Rune = rune, Attribute = color.Value.Normal });
-            }
+            cells.AddRange (Cell.ToCellList (csName, color.Value.Normal));
 
 
-            cells.Add (new () { Rune = (Rune)'\n', Attribute = color.Value.Focus });
+            cells.Add (new () { Grapheme = "\n", Attribute = color.Value.Focus });
         }
         }
 
 
         if (File.Exists (_path))
         if (File.Exists (_path))
@@ -266,10 +265,10 @@ public class SyntaxHighlighting : Scenario
     {
     {
         ClearAllEvents ();
         ClearAllEvents ();
 
 
-        _green = new Attribute (Color.Green, Color.Black);
-        _blue = new Attribute (Color.Blue, Color.Black);
-        _magenta = new Attribute (Color.Magenta, Color.Black);
-        _white = new Attribute (Color.White, Color.Black);
+        _green = new (Color.Green, Color.Black);
+        _blue = new (Color.Blue, Color.Black);
+        _magenta = new (Color.Magenta, Color.Black);
+        _white = new (Color.White, Color.Black);
         _textView.SetScheme (new () { Focus = _white });
         _textView.SetScheme (new () { Focus = _white });
 
 
         _textView.Text =
         _textView.Text =
@@ -290,7 +289,7 @@ public class SyntaxHighlighting : Scenario
         _textView.InheritsPreviousAttribute = false;
         _textView.InheritsPreviousAttribute = false;
     }
     }
 
 
-    private bool ContainsPosition (Match m, int pos) { return pos >= m.Index && pos < m.Index + m.Length; }
+    private bool ContainsPosition (Match m, int pos) => pos >= m.Index && pos < m.Index + m.Length;
 
 
     private void HighlightTextBasedOnKeywords ()
     private void HighlightTextBasedOnKeywords ()
     {
     {
@@ -388,12 +387,6 @@ public class SyntaxHighlighting : Scenario
         List<List<Cell>> cells = _textView.GetAllLines ();
         List<List<Cell>> cells = _textView.GetAllLines ();
         WriteToJsonFile (_path, cells);
         WriteToJsonFile (_path, cells);
     }
     }
-
-    private void WordWrap ()
-    {
-        _miWrap.Checked = !_miWrap.Checked;
-        _textView.WordWrap = (bool)_miWrap.Checked;
-    }
 }
 }
 
 
 public static class EventExtensions
 public static class EventExtensions

+ 151 - 102
Examples/UICatalog/Scenarios/TabViewExample.cs

@@ -1,4 +1,6 @@
-using System.Linq;
+#nullable enable
+
+using System.Linq;
 using System.Text;
 using System.Text;
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
@@ -8,85 +10,41 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("TabView")]
 [ScenarioCategory ("TabView")]
 public class TabViewExample : Scenario
 public class TabViewExample : Scenario
 {
 {
-    private MenuItem _miShowBorder;
-    private MenuItem _miShowTabViewBorder;
-    private MenuItem _miShowTopLine;
-    private MenuItem _miTabsOnBottom;
-    private TabView _tabView;
+    private CheckBox? _miShowBorderCheckBox;
+    private CheckBox? _miShowTabViewBorderCheckBox;
+    private CheckBox? _miShowTopLineCheckBox;
+    private CheckBox? _miTabsOnBottomCheckBox;
+    private TabView? _tabView;
 
 
     public override void Main ()
     public override void Main ()
     {
     {
-        // Init
         Application.Init ();
         Application.Init ();
 
 
-        // Setup - Create a top-level application window and configure it.
-        Toplevel appWindow = new ();
-
-        var menu = new MenuBar
+        Window appWindow = new ()
         {
         {
-            Menus =
-            [
-                new (
-                     "_File",
-                     new MenuItem []
-                     {
-                         new ("_Add Blank Tab", "", AddBlankTab),
-                         new (
-                              "_Clear SelectedTab",
-                              "",
-                              () => _tabView.SelectedTab = null
-                             ),
-                         new ("_Quit", "", Quit)
-                     }
-                    ),
-                new (
-                     "_View",
-                     new []
-                     {
-                         _miShowTopLine =
-                             new ("_Show Top Line", "", ShowTopLine)
-                             {
-                                 Checked = true, CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miShowBorder =
-                             new ("_Show Border", "", ShowBorder)
-                             {
-                                 Checked = true, CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miTabsOnBottom =
-                             new ("_Tabs On Bottom", "", SetTabsOnBottom)
-                             {
-                                 Checked = false, CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miShowTabViewBorder =
-                             new (
-                                  "_Show TabView Border",
-                                  "",
-                                  ShowTabViewBorder
-                                 ) { Checked = true, CheckType = MenuItemCheckStyle.Checked }
-                     }
-                    )
-            ]
+            BorderStyle = LineStyle.None
         };
         };
-        appWindow.Add (menu);
 
 
-        _tabView = new()
+        // MenuBar
+        MenuBar menu = new ();
+
+        _tabView = new ()
         {
         {
             Title = "_Tab View",
             Title = "_Tab View",
             X = 0,
             X = 0,
-            Y = 1,
+            Y = Pos.Bottom (menu),
             Width = 60,
             Width = 60,
             Height = 20,
             Height = 20,
             BorderStyle = LineStyle.Single
             BorderStyle = LineStyle.Single
         };
         };
 
 
-        _tabView.AddTab (new() { DisplayText = "Tab_1", View = new Label { Text = "hodor!" } }, false);
-        _tabView.AddTab (new() { DisplayText = "Tab_2", View = new TextField { Text = "durdur", Width = 10 } }, false);
-        _tabView.AddTab (new() { DisplayText = "_Interactive Tab", View = GetInteractiveTab () }, false);
-        _tabView.AddTab (new() { DisplayText = "Big Text", View = GetBigTextFileTab () }, false);
+        _tabView.AddTab (new () { DisplayText = "Tab_1", View = new Label { Text = "hodor!" } }, false);
+        _tabView.AddTab (new () { DisplayText = "Tab_2", View = new TextField { Text = "durdur", Width = 10 } }, false);
+        _tabView.AddTab (new () { DisplayText = "_Interactive Tab", View = GetInteractiveTab () }, false);
+        _tabView.AddTab (new () { DisplayText = "Big Text", View = GetBigTextFileTab () }, false);
 
 
         _tabView.AddTab (
         _tabView.AddTab (
-                         new()
+                         new ()
                          {
                          {
                              DisplayText =
                              DisplayText =
                                  "Long name Tab, I mean seriously long.  Like you would not believe how long this tab's name is its just too much really woooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooowwww thats long",
                                  "Long name Tab, I mean seriously long.  Like you would not believe how long this tab's name is its just too much really woooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooowwww thats long",
@@ -100,15 +58,16 @@ public class TabViewExample : Scenario
                         );
                         );
 
 
         _tabView.AddTab (
         _tabView.AddTab (
-                         new()
+                         new ()
                          {
                          {
-                             DisplayText = "Les Mise" + '\u0301' + "rables", View = new Label { Text = "This tab name is unicode" }
+                             DisplayText = "Les Mise" + '\u0301' + "rables",
+                             View = new Label { Text = "This tab name is unicode" }
                          },
                          },
                          false
                          false
                         );
                         );
 
 
         _tabView.AddTab (
         _tabView.AddTab (
-                         new()
+                         new ()
                          {
                          {
                              DisplayText = "Les Mise" + '\u0328' + '\u0301' + "rables",
                              DisplayText = "Les Mise" + '\u0328' + '\u0301' + "rables",
                              View = new Label
                              View = new Label
@@ -123,19 +82,17 @@ public class TabViewExample : Scenario
         for (var i = 0; i < 100; i++)
         for (var i = 0; i < 100; i++)
         {
         {
             _tabView.AddTab (
             _tabView.AddTab (
-                             new() { DisplayText = $"Tab{i}", View = new Label { Text = $"Welcome to tab {i}" } },
+                             new () { DisplayText = $"Tab{i}", View = new Label { Text = $"Welcome to tab {i}" } },
                              false
                              false
                             );
                             );
         }
         }
 
 
         _tabView.SelectedTab = _tabView.Tabs.First ();
         _tabView.SelectedTab = _tabView.Tabs.First ();
 
 
-        appWindow.Add (_tabView);
-
-        var frameRight = new View
+        View frameRight = new ()
         {
         {
             X = Pos.Right (_tabView),
             X = Pos.Right (_tabView),
-            Y = 1,
+            Y = Pos.Top (_tabView),
             Width = Dim.Fill (),
             Width = Dim.Fill (),
             Height = Dim.Fill (1),
             Height = Dim.Fill (1),
             Title = "_About",
             Title = "_About",
@@ -147,16 +104,15 @@ public class TabViewExample : Scenario
         frameRight.Add (
         frameRight.Add (
                         new TextView
                         new TextView
                         {
                         {
-                            Text = "This demos the tabs control\nSwitch between tabs using cursor keys.\nThis TextView has AllowsTab = false, so tab should nav too.",
+                            Text =
+                                "This demos the tabs control\nSwitch between tabs using cursor keys.\nThis TextView has AllowsTab = false, so tab should nav too.",
                             Width = Dim.Fill (),
                             Width = Dim.Fill (),
                             Height = Dim.Fill (),
                             Height = Dim.Fill (),
-                            AllowsTab = false,
+                            AllowsTab = false
                         }
                         }
                        );
                        );
 
 
-        appWindow.Add (frameRight);
-
-        var frameBelow = new View
+        View frameBelow = new ()
         {
         {
             X = 0,
             X = 0,
             Y = Pos.Bottom (_tabView),
             Y = Pos.Bottom (_tabView),
@@ -166,7 +122,6 @@ public class TabViewExample : Scenario
             BorderStyle = LineStyle.Single,
             BorderStyle = LineStyle.Single,
             TabStop = TabBehavior.TabStop,
             TabStop = TabBehavior.TabStop,
             CanFocus = true
             CanFocus = true
-
         };
         };
 
 
         frameBelow.Add (
         frameBelow.Add (
@@ -175,31 +130,112 @@ public class TabViewExample : Scenario
                             Text =
                             Text =
                                 "This frame exists to check that you can still tab here\nand that the tab control doesn't overspill it's bounds\nAllowsTab is true.",
                                 "This frame exists to check that you can still tab here\nand that the tab control doesn't overspill it's bounds\nAllowsTab is true.",
                             Width = Dim.Fill (),
                             Width = Dim.Fill (),
-                            Height = Dim.Fill (),
+                            Height = Dim.Fill ()
                         }
                         }
                        );
                        );
 
 
-        appWindow.Add (frameBelow);
+        // StatusBar
+        StatusBar statusBar = new (
+                                   [
+                                       new (Application.QuitKey, "Quit", Quit)
+                                   ]
+                                  );
 
 
-        var statusBar = new StatusBar ([new (Application.QuitKey, "Quit", Quit)]);
-        appWindow.Add (statusBar);
+        // Setup menu checkboxes
+        _miShowTopLineCheckBox = new ()
+        {
+            Title = "_Show Top Line",
+            CheckedState = CheckState.Checked
+        };
+        _miShowTopLineCheckBox.CheckedStateChanged += (s, e) => ShowTopLine ();
 
 
-        // Run - Start the application.
-        Application.Run (appWindow);
+        _miShowBorderCheckBox = new ()
+        {
+            Title = "_Show Border",
+            CheckedState = CheckState.Checked
+        };
+        _miShowBorderCheckBox.CheckedStateChanged += (s, e) => ShowBorder ();
 
 
-        appWindow.Dispose ();
+        _miTabsOnBottomCheckBox = new ()
+        {
+            Title = "_Tabs On Bottom"
+        };
+        _miTabsOnBottomCheckBox.CheckedStateChanged += (s, e) => SetTabsOnBottom ();
+
+        _miShowTabViewBorderCheckBox = new ()
+        {
+            Title = "_Show TabView Border",
+            CheckedState = CheckState.Checked
+        };
+        _miShowTabViewBorderCheckBox.CheckedStateChanged += (s, e) => ShowTabViewBorder ();
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_Add Blank Tab",
+                                           Action = AddBlankTab
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Clear SelectedTab",
+                                           Action = () =>
+                                                    {
+                                                        if (_tabView is { })
+                                                        {
+                                                            _tabView.SelectedTab = null;
+                                                        }
+                                                    }
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Action = Quit
+                                       }
+                                   ]
+                                  )
+                 );
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_View",
+                                   [
+                                       new MenuItem
+                                       {
+                                           CommandView = _miShowTopLineCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miShowBorderCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miTabsOnBottomCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miShowTabViewBorderCheckBox
+                                       }
+                                   ]
+                                  )
+                 );
+
+        appWindow.Add (menu, _tabView, frameRight, frameBelow, statusBar);
 
 
-        // Shutdown - Calling Application.Shutdown is required.
+        Application.Run (appWindow);
+        appWindow.Dispose ();
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
-    private void AddBlankTab () { _tabView.AddTab (new (), false); }
+    private void AddBlankTab () { _tabView?.AddTab (new (), false); }
 
 
     private View GetBigTextFileTab ()
     private View GetBigTextFileTab ()
     {
     {
-        var text = new TextView { Width = Dim.Fill (), Height = Dim.Fill () };
+        TextView text = new () { Width = Dim.Fill (), Height = Dim.Fill () };
 
 
-        var sb = new StringBuilder ();
+        StringBuilder sb = new ();
 
 
         for (var y = 0; y < 300; y++)
         for (var y = 0; y < 300; y++)
         {
         {
@@ -218,21 +254,22 @@ public class TabViewExample : Scenario
 
 
     private View GetInteractiveTab ()
     private View GetInteractiveTab ()
     {
     {
-        var interactiveTab = new View
+        View interactiveTab = new ()
         {
         {
-            Width = Dim.Fill (), Height = Dim.Fill (),
+            Width = Dim.Fill (),
+            Height = Dim.Fill (),
             CanFocus = true
             CanFocus = true
         };
         };
-        var lblName = new Label { Text = "Name:" };
+        Label lblName = new () { Text = "Name:" };
         interactiveTab.Add (lblName);
         interactiveTab.Add (lblName);
 
 
-        var tbName = new TextField { X = Pos.Right (lblName), Width = 10 };
+        TextField tbName = new () { X = Pos.Right (lblName), Width = 10 };
         interactiveTab.Add (tbName);
         interactiveTab.Add (tbName);
 
 
-        var lblAddr = new Label { Y = 1, Text = "Address:" };
+        Label lblAddr = new () { Y = 1, Text = "Address:" };
         interactiveTab.Add (lblAddr);
         interactiveTab.Add (lblAddr);
 
 
-        var tbAddr = new TextField { X = Pos.Right (lblAddr), Y = 1, Width = 10 };
+        TextField tbAddr = new () { X = Pos.Right (lblAddr), Y = 1, Width = 10 };
         interactiveTab.Add (tbAddr);
         interactiveTab.Add (tbAddr);
 
 
         return interactiveTab;
         return interactiveTab;
@@ -242,35 +279,47 @@ public class TabViewExample : Scenario
 
 
     private void SetTabsOnBottom ()
     private void SetTabsOnBottom ()
     {
     {
-        _miTabsOnBottom.Checked = !_miTabsOnBottom.Checked;
+        if (_tabView is null || _miTabsOnBottomCheckBox is null)
+        {
+            return;
+        }
 
 
-        _tabView.Style.TabsOnBottom = (bool)_miTabsOnBottom.Checked;
+        _tabView.Style.TabsOnBottom = _miTabsOnBottomCheckBox.CheckedState == CheckState.Checked;
         _tabView.ApplyStyleChanges ();
         _tabView.ApplyStyleChanges ();
     }
     }
 
 
     private void ShowBorder ()
     private void ShowBorder ()
     {
     {
-        _miShowBorder.Checked = !_miShowBorder.Checked;
+        if (_tabView is null || _miShowBorderCheckBox is null)
+        {
+            return;
+        }
 
 
-        _tabView.Style.ShowBorder = (bool)_miShowBorder.Checked;
+        _tabView.Style.ShowBorder = _miShowBorderCheckBox.CheckedState == CheckState.Checked;
         _tabView.ApplyStyleChanges ();
         _tabView.ApplyStyleChanges ();
     }
     }
 
 
     private void ShowTabViewBorder ()
     private void ShowTabViewBorder ()
     {
     {
-        _miShowTabViewBorder.Checked = !_miShowTabViewBorder.Checked;
+        if (_tabView is null || _miShowTabViewBorderCheckBox is null)
+        {
+            return;
+        }
 
 
-        _tabView.BorderStyle = _miShowTabViewBorder.Checked == true
-                                   ? _tabView.BorderStyle = LineStyle.Single
+        _tabView.BorderStyle = _miShowTabViewBorderCheckBox.CheckedState == CheckState.Checked
+                                   ? LineStyle.Single
                                    : LineStyle.None;
                                    : LineStyle.None;
         _tabView.ApplyStyleChanges ();
         _tabView.ApplyStyleChanges ();
     }
     }
 
 
     private void ShowTopLine ()
     private void ShowTopLine ()
     {
     {
-        _miShowTopLine.Checked = !_miShowTopLine.Checked;
+        if (_tabView is null || _miShowTopLineCheckBox is null)
+        {
+            return;
+        }
 
 
-        _tabView.Style.ShowTopLine = (bool)_miShowTopLine.Checked;
+        _tabView.Style.ShowTopLine = _miShowTopLineCheckBox.CheckedState == CheckState.Checked;
         _tabView.ApplyStyleChanges ();
         _tabView.ApplyStyleChanges ();
     }
     }
 }
 }

+ 327 - 451
Examples/UICatalog/Scenarios/TableEditor.cs

@@ -1,4 +1,4 @@
-#nullable enable
+#nullable enable
 using System.Data;
 using System.Data;
 using System.Globalization;
 using System.Globalization;
 using System.Text;
 using System.Text;
@@ -458,22 +458,6 @@ public class TableEditor : Scenario
 
 
     private Scheme? _alternatingScheme;
     private Scheme? _alternatingScheme;
     private DataTable? _currentTable;
     private DataTable? _currentTable;
-    private MenuItem? _miAlternatingColors;
-    private MenuItem? _miAlwaysShowHeaders;
-    private MenuItem? _miAlwaysUseNormalColorForVerticalCellLines;
-    private MenuItem? _miBottomline;
-    private MenuItem? _miCellLines;
-    private MenuItem? _miCheckboxes;
-    private MenuItem? _miCursor;
-    private MenuItem? _miExpandLastColumn;
-    private MenuItem? _miFullRowSelect;
-    private MenuItem? _miHeaderMidline;
-    private MenuItem? _miHeaderOverline;
-    private MenuItem? _miHeaderUnderline;
-    private MenuItem? _miRadioboxes;
-    private MenuItem? _miShowHeaders;
-    private MenuItem? _miShowHorizontalScrollIndicators;
-    private MenuItem? _miSmoothScrolling;
     private Scheme? _redScheme;
     private Scheme? _redScheme;
     private Scheme? _redSchemeAlt;
     private Scheme? _redSchemeAlt;
     private TableView? _tableView;
     private TableView? _tableView;
@@ -515,243 +499,42 @@ public class TableEditor : Scenario
         Application.Init ();
         Application.Init ();
 
 
         // Setup - Create a top-level application window and configure it.
         // Setup - Create a top-level application window and configure it.
-        Toplevel appWindow = new ();
+        Runnable appWindow = new ();
 
 
         _tableView = new () { X = 0, Y = 1, Width = Dim.Fill (), Height = Dim.Fill (1) };
         _tableView = new () { X = 0, Y = 1, Width = Dim.Fill (), Height = Dim.Fill (1) };
 
 
-        var menu = new MenuBar
-        {
-            Menus =
-            [
-                new (
-                     "_File",
-                     new MenuItem []
-                     {
-                         new (
-                              "_OpenBigExample",
-                              "",
-                              () => OpenExample (true)
-                             ),
-                         new (
-                              "_OpenSmallExample",
-                              "",
-                              () => OpenExample (false)
-                             ),
-                         new (
-                              "OpenCharacter_Map",
-                              "",
-                              () => OpenUnicodeMap ()
-                             ),
-                         new (
-                              "OpenTreeExample",
-                              "",
-                              () => OpenTreeExample ()
-                             ),
-                         new (
-                              "_CloseExample",
-                              "",
-                              () => CloseExample ()
-                             ),
-                         new ("_Quit", "", () => Quit ())
-                     }
-                    ),
-                new (
-                     "_View",
-                     new []
-                     {
-                         _miShowHeaders =
-                             new (
-                                  "_ShowHeaders",
-                                  "",
-                                  () => ToggleShowHeaders ()
-                                 )
-                             {
-                                 Checked = _tableView!.Style.ShowHeaders,
-                                 CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miAlwaysShowHeaders =
-                             new (
-                                  "_AlwaysShowHeaders",
-                                  "",
-                                  () => ToggleAlwaysShowHeaders ()
-                                 )
-                             {
-                                 Checked = _tableView!.Style.AlwaysShowHeaders,
-                                 CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miHeaderOverline =
-                             new (
-                                  "_HeaderOverLine",
-                                  "",
-                                  () => ToggleOverline ()
-                                 )
-                             {
-                                 Checked = _tableView!.Style
-                                                     .ShowHorizontalHeaderOverline,
-                                 CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miHeaderMidline = new (
-                                                 "_HeaderMidLine",
-                                                 "",
-                                                 () => ToggleHeaderMidline ()
-                                                )
-                         {
-                             Checked = _tableView!.Style
-                                                 .ShowVerticalHeaderLines,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         _miHeaderUnderline = new (
-                                                   "_HeaderUnderLine",
-                                                   "",
-                                                   () => ToggleUnderline ()
-                                                  )
-                         {
-                             Checked = _tableView!.Style
-                                                 .ShowHorizontalHeaderUnderline,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         _miBottomline = new (
-                                              "_BottomLine",
-                                              "",
-                                              () => ToggleBottomline ()
-                                             )
-                         {
-                             Checked = _tableView!.Style
-                                                 .ShowHorizontalBottomline,
-                             CheckType = MenuItemCheckStyle
-                                 .Checked
-                         },
-                         _miShowHorizontalScrollIndicators =
-                             new (
-                                  "_HorizontalScrollIndicators",
-                                  "",
-                                  () =>
-                                      ToggleHorizontalScrollIndicators ()
-                                 )
-                             {
-                                 Checked = _tableView!.Style
-                                                     .ShowHorizontalScrollIndicators,
-                                 CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miFullRowSelect = new (
-                                                 "_FullRowSelect",
-                                                 "",
-                                                 () => ToggleFullRowSelect ()
-                                                )
-                         {
-                             Checked = _tableView!.FullRowSelect,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         _miCellLines = new (
-                                             "_CellLines",
-                                             "",
-                                             () => ToggleCellLines ()
-                                            )
-                         {
-                             Checked = _tableView!.Style
-                                                 .ShowVerticalCellLines,
-                             CheckType = MenuItemCheckStyle
-                                 .Checked
-                         },
-                         _miExpandLastColumn =
-                             new (
-                                  "_ExpandLastColumn",
-                                  "",
-                                  () => ToggleExpandLastColumn ()
-                                 )
-                             {
-                                 Checked = _tableView!.Style.ExpandLastColumn,
-                                 CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miAlwaysUseNormalColorForVerticalCellLines =
-                             new (
-                                  "_AlwaysUseNormalColorForVerticalCellLines",
-                                  "",
-                                  () =>
-                                      ToggleAlwaysUseNormalColorForVerticalCellLines ()
-                                 )
-                             {
-                                 Checked = _tableView!.Style
-                                                     .AlwaysUseNormalColorForVerticalCellLines,
-                                 CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miSmoothScrolling =
-                             new (
-                                  "_SmoothHorizontalScrolling",
-                                  "",
-                                  () => ToggleSmoothScrolling ()
-                                 )
-                             {
-                                 Checked = _tableView!.Style
-                                                     .SmoothHorizontalScrolling,
-                                 CheckType = MenuItemCheckStyle.Checked
-                             },
-                         new ("_AllLines", "", () => ToggleAllCellLines ()),
-                         new ("_NoLines", "", () => ToggleNoCellLines ()),
-                         _miCheckboxes = new (
-                                              "_Checkboxes",
-                                              "",
-                                              () => ToggleCheckboxes (false)
-                                             )
-                         {
-                             Checked = false,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         _miRadioboxes = new (
-                                              "_Radioboxes",
-                                              "",
-                                              () => ToggleCheckboxes (true)
-                                             )
-                         {
-                             Checked = false,
-                             CheckType = MenuItemCheckStyle.Checked
-                         },
-                         _miAlternatingColors =
-                             new (
-                                  "Alternating Colors",
-                                  "",
-                                  () => ToggleAlternatingColors ()
-                                 ) { CheckType = MenuItemCheckStyle.Checked },
-                         _miCursor =
-                             new (
-                                  "Invert Selected Cell First Character",
-                                  "",
-                                  () =>
-                                      ToggleInvertSelectedCellFirstCharacter ()
-                                 )
-                             {
-                                 Checked = _tableView!.Style
-                                                     .InvertSelectedCellFirstCharacter,
-                                 CheckType = MenuItemCheckStyle.Checked
-                             },
-                         new (
-                              "_ClearColumnStyles",
-                              "",
-                              () => ClearColumnStyles ()
-                             ),
-                         new ("Sho_w All Columns", "", () => ShowAllColumns ())
-                     }
-                    ),
-                new (
-                     "_Column",
-                     new MenuItem []
-                     {
-                         new ("_Set Max Width", "", SetMaxWidth),
-                         new ("_Set Min Width", "", SetMinWidth),
-                         new (
-                              "_Set MinAcceptableWidth",
-                              "",
-                              SetMinAcceptableWidth
-                             ),
-                         new (
-                              "_Set All MinAcceptableWidth=1",
-                              "",
-                              SetMinAcceptableWidthToOne
-                             )
-                     }
-                    )
-            ]
-        };
+        var menu = new MenuBar ();
+
+        // File menu
+        menu.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuItem { Title = "_OpenBigExample", Action = () => OpenExample (true) },
+                                       new MenuItem { Title = "_OpenSmallExample", Action = () => OpenExample (false) },
+                                       new MenuItem { Title = "OpenCharacter_Map", Action = OpenUnicodeMap },
+                                       new MenuItem { Title = "OpenTreeExample", Action = OpenTreeExample },
+                                       new MenuItem { Title = "_CloseExample", Action = CloseExample },
+                                       new MenuItem { Title = "_Quit", Action = Quit }
+                                   ]
+                                  )
+                 );
+
+        // View menu - created with helper method due to complexity
+        menu.Add (CreateViewMenu ());
+
+        // Column menu
+        menu.Add (
+                  new MenuBarItem (
+                                   "_Column",
+                                   [
+                                       new MenuItem { Title = "_Set Max Width", Action = SetMaxWidth },
+                                       new MenuItem { Title = "_Set Min Width", Action = SetMinWidth },
+                                       new MenuItem { Title = "_Set MinAcceptableWidth", Action = SetMinAcceptableWidth },
+                                       new MenuItem { Title = "_Set All MinAcceptableWidth=1", Action = SetMinAcceptableWidthToOne }
+                                   ]
+                                  )
+                 );
 
 
         appWindow.Add (menu);
         appWindow.Add (menu);
 
 
@@ -828,28 +611,28 @@ public class TableEditor : Scenario
 
 
         // if user clicks the mouse in TableView
         // if user clicks the mouse in TableView
         _tableView!.MouseClick += (s, e) =>
         _tableView!.MouseClick += (s, e) =>
-                                 {
-                                     if (_currentTable == null)
-                                     {
-                                         return;
-                                     }
-
-                                     _tableView!.ScreenToCell (e.Position, out int? clickedCol);
-
-                                     if (clickedCol != null)
-                                     {
-                                         if (e.Flags.HasFlag (MouseFlags.Button1Clicked))
-                                         {
-                                             // left click in a header
-                                             SortColumn (clickedCol.Value);
-                                         }
-                                         else if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
-                                         {
-                                             // right click in a header
-                                             ShowHeaderContextMenu (clickedCol.Value, e);
-                                         }
-                                     }
-                                 };
+                                  {
+                                      if (_currentTable == null)
+                                      {
+                                          return;
+                                      }
+
+                                      _tableView!.ScreenToCell (e.Position, out int? clickedCol);
+
+                                      if (clickedCol != null)
+                                      {
+                                          if (e.Flags.HasFlag (MouseFlags.Button1Clicked))
+                                          {
+                                              // left click in a header
+                                              SortColumn (clickedCol.Value);
+                                          }
+                                          else if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
+                                          {
+                                              // right click in a header
+                                              ShowHeaderContextMenu (clickedCol.Value, e);
+                                          }
+                                      }
+                                  };
 
 
         _tableView!.KeyBindings.ReplaceCommands (Key.Space, Command.Accept);
         _tableView!.KeyBindings.ReplaceCommands (Key.Space, Command.Accept);
 
 
@@ -861,6 +644,261 @@ public class TableEditor : Scenario
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
+    private MenuBarItem CreateViewMenu ()
+    {
+        // Store checkbox references for the toggle methods to access
+        Dictionary<string, CheckBox> checkboxes = new ();
+
+        MenuItem CreateCheckBoxMenuItem (string key, string title, bool initialState, Action<bool> onToggle)
+        {
+            CheckBox checkBox = new ()
+            {
+                Title = title,
+                CheckedState = initialState ? CheckState.Checked : CheckState.UnChecked
+            };
+
+            checkBox.CheckedStateChanged += (s, e) => onToggle (checkBox.CheckedState == CheckState.Checked);
+
+            MenuItem item = new () { CommandView = checkBox };
+
+            item.Accepting += (s, e) =>
+                              {
+                                  checkBox.AdvanceCheckState ();
+                                  e.Handled = true;
+                              };
+
+            checkboxes [key] = checkBox;
+
+            return item;
+        }
+
+        return new (
+                    "_View",
+                    [
+                        CreateCheckBoxMenuItem (
+                                                "ShowHeaders",
+                                                "_ShowHeaders",
+                                                _tableView!.Style.ShowHeaders,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.ShowHeaders = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "AlwaysShowHeaders",
+                                                "_AlwaysShowHeaders",
+                                                _tableView!.Style.AlwaysShowHeaders,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.AlwaysShowHeaders = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "HeaderOverline",
+                                                "_HeaderOverLine",
+                                                _tableView!.Style.ShowHorizontalHeaderOverline,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.ShowHorizontalHeaderOverline = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "HeaderMidline",
+                                                "_HeaderMidLine",
+                                                _tableView!.Style.ShowVerticalHeaderLines,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.ShowVerticalHeaderLines = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "HeaderUnderline",
+                                                "_HeaderUnderLine",
+                                                _tableView!.Style.ShowHorizontalHeaderUnderline,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.ShowHorizontalHeaderUnderline = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "Bottomline",
+                                                "_BottomLine",
+                                                _tableView!.Style.ShowHorizontalBottomline,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.ShowHorizontalBottomline = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "HorizontalScrollIndicators",
+                                                "_HorizontalScrollIndicators",
+                                                _tableView!.Style.ShowHorizontalScrollIndicators,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.ShowHorizontalScrollIndicators = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "FullRowSelect",
+                                                "_FullRowSelect",
+                                                _tableView!.FullRowSelect,
+                                                state =>
+                                                {
+                                                    _tableView!.FullRowSelect = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "CellLines",
+                                                "_CellLines",
+                                                _tableView!.Style.ShowVerticalCellLines,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.ShowVerticalCellLines = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "ExpandLastColumn",
+                                                "_ExpandLastColumn",
+                                                _tableView!.Style.ExpandLastColumn,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.ExpandLastColumn = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "AlwaysUseNormalColorForVerticalCellLines",
+                                                "_AlwaysUseNormalColorForVerticalCellLines",
+                                                _tableView!.Style.AlwaysUseNormalColorForVerticalCellLines,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.AlwaysUseNormalColorForVerticalCellLines = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "SmoothScrolling",
+                                                "_SmoothHorizontalScrolling",
+                                                _tableView!.Style.SmoothHorizontalScrolling,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.SmoothHorizontalScrolling = state;
+                                                    _tableView!.Update ();
+                                                }
+                                               ),
+                        new MenuItem
+                        {
+                            Title = "_AllLines",
+                            Action = () =>
+                                     {
+                                         _tableView!.Style.ShowHorizontalHeaderOverline = true;
+                                         _tableView!.Style.ShowVerticalHeaderLines = true;
+                                         _tableView!.Style.ShowHorizontalHeaderUnderline = true;
+                                         _tableView!.Style.ShowVerticalCellLines = true;
+
+                                         checkboxes ["HeaderOverline"].CheckedState = CheckState.Checked;
+                                         checkboxes ["HeaderMidline"].CheckedState = CheckState.Checked;
+                                         checkboxes ["HeaderUnderline"].CheckedState = CheckState.Checked;
+                                         checkboxes ["CellLines"].CheckedState = CheckState.Checked;
+
+                                         _tableView!.Update ();
+                                     }
+                        },
+                        new MenuItem
+                        {
+                            Title = "_NoLines",
+                            Action = () =>
+                                     {
+                                         _tableView!.Style.ShowHorizontalHeaderOverline = false;
+                                         _tableView!.Style.ShowVerticalHeaderLines = false;
+                                         _tableView!.Style.ShowHorizontalHeaderUnderline = false;
+                                         _tableView!.Style.ShowVerticalCellLines = false;
+
+                                         checkboxes ["HeaderOverline"].CheckedState = CheckState.UnChecked;
+                                         checkboxes ["HeaderMidline"].CheckedState = CheckState.UnChecked;
+                                         checkboxes ["HeaderUnderline"].CheckedState = CheckState.UnChecked;
+                                         checkboxes ["CellLines"].CheckedState = CheckState.UnChecked;
+
+                                         _tableView!.Update ();
+                                     }
+                        },
+                        CreateCheckBoxMenuItem (
+                                                "Checkboxes",
+                                                "_Checkboxes",
+                                                false,
+                                                state =>
+                                                {
+                                                    if (state)
+                                                    {
+                                                        ToggleCheckboxes (false);
+                                                        checkboxes ["Radioboxes"].CheckedState = CheckState.UnChecked;
+                                                    }
+                                                    else if (HasCheckboxes ())
+                                                    {
+                                                        ToggleCheckboxes (false);
+                                                    }
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "Radioboxes",
+                                                "_Radioboxes",
+                                                false,
+                                                state =>
+                                                {
+                                                    if (state)
+                                                    {
+                                                        ToggleCheckboxes (true);
+                                                        checkboxes ["Checkboxes"].CheckedState = CheckState.UnChecked;
+                                                    }
+                                                    else if (HasCheckboxes ())
+                                                    {
+                                                        ToggleCheckboxes (true);
+                                                    }
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "AlternatingColors",
+                                                "Alternating Colors",
+                                                false,
+                                                state =>
+                                                {
+                                                    if (state)
+                                                    {
+                                                        _tableView!.Style.RowColorGetter = a => { return a.RowIndex % 2 == 0 ? _alternatingScheme : null; };
+                                                    }
+                                                    else
+                                                    {
+                                                        _tableView!.Style.RowColorGetter = null;
+                                                    }
+
+                                                    _tableView!.SetNeedsDraw ();
+                                                }
+                                               ),
+                        CreateCheckBoxMenuItem (
+                                                "Cursor",
+                                                "Invert Selected Cell First Character",
+                                                _tableView!.Style.InvertSelectedCellFirstCharacter,
+                                                state =>
+                                                {
+                                                    _tableView!.Style.InvertSelectedCellFirstCharacter = state;
+                                                    _tableView!.SetNeedsDraw ();
+                                                }
+                                               ),
+                        new MenuItem { Title = "_ClearColumnStyles", Action = ClearColumnStyles },
+                        new MenuItem { Title = "Sho_w All Columns", Action = ShowAllColumns }
+                    ]
+                   );
+    }
+
     protected override void Dispose (bool disposing)
     protected override void Dispose (bool disposing)
     {
     {
         base.Dispose (disposing);
         base.Dispose (disposing);
@@ -988,7 +1026,7 @@ public class TableEditor : Scenario
             }
             }
             catch (Exception ex)
             catch (Exception ex)
             {
             {
-                MessageBox.ErrorQuery (60, 20, "Failed to set text", ex.Message, "Ok");
+                MessageBox.ErrorQuery ((sender as View)?.App, 60, 20, "Failed to set text", ex.Message, "Ok");
             }
             }
 
 
             _tableView!.Update ();
             _tableView!.Update ();
@@ -1078,7 +1116,7 @@ public class TableEditor : Scenario
     }
     }
 
 
     private string GetUnicodeCategory (uint u) { return _ranges!.FirstOrDefault (r => u >= r.Start && u <= r.End)?.Category ?? "Unknown"; }
     private string GetUnicodeCategory (uint u) { return _ranges!.FirstOrDefault (r => u >= r.Start && u <= r.End)?.Category ?? "Unknown"; }
-    private bool HasCheckboxes () { return _tableView!.Table is CheckBoxTableSourceWrapperBase; }
+    private bool HasCheckboxes () => _tableView!.Table is CheckBoxTableSourceWrapperBase;
 
 
     private void HideColumn (int clickedCol)
     private void HideColumn (int clickedCol)
     {
     {
@@ -1127,7 +1165,7 @@ public class TableEditor : Scenario
         }
         }
         catch (Exception e)
         catch (Exception e)
         {
         {
-            MessageBox.ErrorQuery ("Could not find local drives", e.Message, "Ok");
+            MessageBox.ErrorQuery (_tableView?.App, "Could not find local drives", e.Message, "Ok");
         }
         }
 
 
         _tableView!.Table = source;
         _tableView!.Table = source;
@@ -1161,10 +1199,10 @@ public class TableEditor : Scenario
         ok.Accepting += (s, e) =>
         ok.Accepting += (s, e) =>
                         {
                         {
                             accepted = true;
                             accepted = true;
-                            Application.RequestStop ();
+                            (s as View)?.App?.RequestStop ();
                         };
                         };
         var cancel = new Button { Text = "Cancel" };
         var cancel = new Button { Text = "Cancel" };
-        cancel.Accepting += (s, e) => { Application.RequestStop (); };
+        cancel.Accepting += (s, e) => { (s as View)?.App?.RequestStop (); };
 
 
         var d = new Dialog
         var d = new Dialog
         {
         {
@@ -1180,7 +1218,7 @@ public class TableEditor : Scenario
         d.Add (lbl, tf);
         d.Add (lbl, tf);
         tf.SetFocus ();
         tf.SetFocus ();
 
 
-        Application.Run (d);
+        _tableView.App?.Run (d);
         d.Dispose ();
         d.Dispose ();
 
 
         if (accepted)
         if (accepted)
@@ -1191,7 +1229,7 @@ public class TableEditor : Scenario
             }
             }
             catch (Exception ex)
             catch (Exception ex)
             {
             {
-                MessageBox.ErrorQuery (60, 20, "Failed to set", ex.Message, "Ok");
+                MessageBox.ErrorQuery (_tableView.App, 60, 20, "Failed to set", ex.Message, "Ok");
             }
             }
 
 
             _tableView!.Update ();
             _tableView!.Update ();
@@ -1236,7 +1274,6 @@ public class TableEditor : Scenario
                                    // color 0 and negative values red
                                    // color 0 and negative values red
                                    d <= 0.0000001
                                    d <= 0.0000001
                                        ? a.RowIndex % 2 == 0
                                        ? a.RowIndex % 2 == 0
-                                         && _miAlternatingColors!.Checked == true
                                              ? _redSchemeAlt
                                              ? _redSchemeAlt
                                              : _redScheme
                                              : _redScheme
                                        :
                                        :
@@ -1414,7 +1451,7 @@ public class TableEditor : Scenario
         _tableView!.Update ();
         _tableView!.Update ();
     }
     }
 
 
-    private string StripArrows (string columnName) { return columnName.Replace ($"{Glyphs.DownArrow}", "").Replace ($"{Glyphs.UpArrow}", ""); }
+    private string StripArrows (string columnName) => columnName.Replace ($"{Glyphs.DownArrow}", "").Replace ($"{Glyphs.UpArrow}", "");
 
 
     private void TableViewKeyPress (object? sender, Key e)
     private void TableViewKeyPress (object? sender, Key e)
     {
     {
@@ -1429,9 +1466,9 @@ public class TableEditor : Scenario
             {
             {
                 // Delete button deletes all rows when in full row mode
                 // Delete button deletes all rows when in full row mode
                 foreach (int toRemove in _tableView!.GetAllSelectedCells ()
                 foreach (int toRemove in _tableView!.GetAllSelectedCells ()
-                                                   .Select (p => p.Y)
-                                                   .Distinct ()
-                                                   .OrderByDescending (i => i))
+                                                    .Select (p => p.Y)
+                                                    .Distinct ()
+                                                    .OrderByDescending (i => i))
                 {
                 {
                     _currentTable.Rows.RemoveAt (toRemove);
                     _currentTable.Rows.RemoveAt (toRemove);
                 }
                 }
@@ -1450,70 +1487,6 @@ public class TableEditor : Scenario
         }
         }
     }
     }
 
 
-    private void ToggleAllCellLines ()
-    {
-        _tableView!.Style.ShowHorizontalHeaderOverline = true;
-        _tableView!.Style.ShowVerticalHeaderLines = true;
-        _tableView!.Style.ShowHorizontalHeaderUnderline = true;
-        _tableView!.Style.ShowVerticalCellLines = true;
-
-        _miHeaderOverline!.Checked = true;
-        _miHeaderMidline!.Checked = true;
-        _miHeaderUnderline!.Checked = true;
-        _miCellLines!.Checked = true;
-
-        _tableView!.Update ();
-    }
-
-    private void ToggleAlternatingColors ()
-    {
-        //toggle menu item
-        _miAlternatingColors!.Checked = !_miAlternatingColors.Checked;
-
-        if (_miAlternatingColors.Checked == true)
-        {
-            _tableView!.Style.RowColorGetter = a => { return a.RowIndex % 2 == 0 ? _alternatingScheme : null; };
-        }
-        else
-        {
-            _tableView!.Style.RowColorGetter = null;
-        }
-
-        _tableView!.SetNeedsDraw ();
-    }
-
-    private void ToggleAlwaysShowHeaders ()
-    {
-        _miAlwaysShowHeaders!.Checked = !_miAlwaysShowHeaders.Checked;
-        _tableView!.Style.AlwaysShowHeaders = (bool)_miAlwaysShowHeaders.Checked!;
-        _tableView!.Update ();
-    }
-
-    private void ToggleAlwaysUseNormalColorForVerticalCellLines ()
-    {
-        _miAlwaysUseNormalColorForVerticalCellLines!.Checked =
-            !_miAlwaysUseNormalColorForVerticalCellLines.Checked;
-
-        _tableView!.Style.AlwaysUseNormalColorForVerticalCellLines =
-            (bool)_miAlwaysUseNormalColorForVerticalCellLines.Checked!;
-
-        _tableView!.Update ();
-    }
-
-    private void ToggleBottomline ()
-    {
-        _miBottomline!.Checked = !_miBottomline.Checked;
-        _tableView!.Style.ShowHorizontalBottomline = (bool)_miBottomline.Checked!;
-        _tableView!.Update ();
-    }
-
-    private void ToggleCellLines ()
-    {
-        _miCellLines!.Checked = !_miCellLines.Checked;
-        _tableView!.Style.ShowVerticalCellLines = (bool)_miCellLines.Checked!;
-        _tableView!.Update ();
-    }
-
     private void ToggleCheckboxes (bool radio)
     private void ToggleCheckboxes (bool radio)
     {
     {
         if (_tableView!.Table is CheckBoxTableSourceWrapperBase wrapper)
         if (_tableView!.Table is CheckBoxTableSourceWrapperBase wrapper)
@@ -1521,9 +1494,6 @@ public class TableEditor : Scenario
             // unwrap it to remove check boxes
             // unwrap it to remove check boxes
             _tableView!.Table = wrapper.Wrapping;
             _tableView!.Table = wrapper.Wrapping;
 
 
-            _miCheckboxes!.Checked = false;
-            _miRadioboxes!.Checked = false;
-
             // if toggling off checkboxes/radio
             // if toggling off checkboxes/radio
             if (wrapper.UseRadioButtons == radio)
             if (wrapper.UseRadioButtons == radio)
             {
             {
@@ -1550,98 +1520,6 @@ public class TableEditor : Scenario
         }
         }
 
 
         _tableView!.Table = source;
         _tableView!.Table = source;
-
-        if (radio)
-        {
-            _miRadioboxes!.Checked = true;
-            _miCheckboxes!.Checked = false;
-        }
-        else
-        {
-            _miRadioboxes!.Checked = false;
-            _miCheckboxes!.Checked = true;
-        }
-    }
-
-    private void ToggleExpandLastColumn ()
-    {
-        _miExpandLastColumn!.Checked = !_miExpandLastColumn.Checked;
-        _tableView!.Style.ExpandLastColumn = (bool)_miExpandLastColumn.Checked!;
-
-        _tableView!.Update ();
-    }
-
-    private void ToggleFullRowSelect ()
-    {
-        _miFullRowSelect!.Checked = !_miFullRowSelect.Checked;
-        _tableView!.FullRowSelect = (bool)_miFullRowSelect.Checked!;
-        _tableView!.Update ();
-    }
-
-    private void ToggleHeaderMidline ()
-    {
-        _miHeaderMidline!.Checked = !_miHeaderMidline.Checked;
-        _tableView!.Style.ShowVerticalHeaderLines = (bool)_miHeaderMidline.Checked!;
-        _tableView!.Update ();
-    }
-
-    private void ToggleHorizontalScrollIndicators ()
-    {
-        _miShowHorizontalScrollIndicators!.Checked = !_miShowHorizontalScrollIndicators.Checked;
-        _tableView!.Style.ShowHorizontalScrollIndicators = (bool)_miShowHorizontalScrollIndicators.Checked!;
-        _tableView!.Update ();
-    }
-
-    private void ToggleInvertSelectedCellFirstCharacter ()
-    {
-        //toggle menu item
-        _miCursor!.Checked = !_miCursor.Checked;
-        _tableView!.Style.InvertSelectedCellFirstCharacter = (bool)_miCursor.Checked!;
-        _tableView!.SetNeedsDraw ();
-    }
-
-    private void ToggleNoCellLines ()
-    {
-        _tableView!.Style.ShowHorizontalHeaderOverline = false;
-        _tableView!.Style.ShowVerticalHeaderLines = false;
-        _tableView!.Style.ShowHorizontalHeaderUnderline = false;
-        _tableView!.Style.ShowVerticalCellLines = false;
-
-        _miHeaderOverline!.Checked = false;
-        _miHeaderMidline!.Checked = false;
-        _miHeaderUnderline!.Checked = false;
-        _miCellLines!.Checked = false;
-
-        _tableView!.Update ();
-    }
-
-    private void ToggleOverline ()
-    {
-        _miHeaderOverline!.Checked = !_miHeaderOverline.Checked;
-        _tableView!.Style.ShowHorizontalHeaderOverline = (bool)_miHeaderOverline.Checked!;
-        _tableView!.Update ();
-    }
-
-    private void ToggleShowHeaders ()
-    {
-        _miShowHeaders!.Checked = !_miShowHeaders.Checked;
-        _tableView!.Style.ShowHeaders = (bool)_miShowHeaders.Checked!;
-        _tableView!.Update ();
-    }
-
-    private void ToggleSmoothScrolling ()
-    {
-        _miSmoothScrolling!.Checked = !_miSmoothScrolling.Checked;
-        _tableView!.Style.SmoothHorizontalScrolling = (bool)_miSmoothScrolling.Checked!;
-
-        _tableView!.Update ();
-    }
-
-    private void ToggleUnderline ()
-    {
-        _miHeaderUnderline!.Checked = !_miHeaderUnderline.Checked;
-        _tableView!.Style.ShowHorizontalHeaderUnderline = (bool)_miHeaderUnderline.Checked!;
-        _tableView!.Update ();
     }
     }
 
 
     private int ToTableCol (int col)
     private int ToTableCol (int col)
@@ -1654,13 +1532,11 @@ public class TableEditor : Scenario
         return col;
         return col;
     }
     }
 
 
-    private string TrimArrows (string columnName)
-    {
-        return columnName.TrimEnd (
-                                   (char)Glyphs.UpArrow.Value,
-                                   (char)Glyphs.DownArrow.Value
-                                  );
-    }
+    private string TrimArrows (string columnName) =>
+        columnName.TrimEnd (
+                            (char)Glyphs.UpArrow.Value,
+                            (char)Glyphs.DownArrow.Value
+                           );
 
 
     public class UnicodeRange (uint start, uint end, string category)
     public class UnicodeRange (uint start, uint end, string category)
     {
     {

+ 3 - 6
Examples/UICatalog/Scenarios/TextEffectsScenario.cs

@@ -23,14 +23,11 @@ public class TextEffectsScenario : Scenario
             Title = "Text Effects Scenario"
             Title = "Text Effects Scenario"
         };
         };
 
 
-        w.Loaded += (s, e) => { SetupGradientLineCanvas (w, w.Frame.Size); };
+        w.IsModalChanged += (s, e) => { SetupGradientLineCanvas (w, w.Frame.Size); };
 
 
-        w.SizeChanging += (s, e) =>
+        w.ViewportChanged += (s, e) =>
                           {
                           {
-                              if (e.Size.HasValue)
-                              {
-                                  SetupGradientLineCanvas (w, e.Size.Value);
-                              }
+                              SetupGradientLineCanvas (w, e.NewViewport.Size);
                           };
                           };
 
 
         w.SetScheme (new ()
         w.SetScheme (new ()

+ 1 - 1
Examples/UICatalog/Scenarios/TextFormatterDemo.cs

@@ -30,7 +30,7 @@ public class TextFormatterDemo : Scenario
 
 
         var blockText = new Label
         var blockText = new Label
         {
         {
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             X = 0,
             X = 0,
             Y = 0,
             Y = 0,
 
 

+ 1 - 1
Examples/UICatalog/Scenarios/TextStyles.cs

@@ -5,7 +5,7 @@ namespace UICatalog.Scenarios;
 [ScenarioMetadata ("Text Styles", "Shows Attribute.TextStyles including bold, italic, etc...")]
 [ScenarioMetadata ("Text Styles", "Shows Attribute.TextStyles including bold, italic, etc...")]
 [ScenarioCategory ("Text and Formatting")]
 [ScenarioCategory ("Text and Formatting")]
 [ScenarioCategory ("Colors")]
 [ScenarioCategory ("Colors")]
-public sealed class TestStyles : Scenario
+public sealed class TextStyles : Scenario
 {
 {
     private CheckBox? _drawDirectly;
     private CheckBox? _drawDirectly;
 
 

+ 187 - 94
Examples/UICatalog/Scenarios/TextViewAutocompletePopup.cs

@@ -1,4 +1,5 @@
-using System.Linq;
+#nullable enable
+
 using System.Text.RegularExpressions;
 using System.Text.RegularExpressions;
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
@@ -10,77 +11,63 @@ namespace UICatalog.Scenarios;
 public class TextViewAutocompletePopup : Scenario
 public class TextViewAutocompletePopup : Scenario
 {
 {
     private int _height = 10;
     private int _height = 10;
-    private MenuItem _miMultiline;
-    private MenuItem _miWrap;
-    private Shortcut _siMultiline;
-    private Shortcut _siWrap;
-    private TextView _textViewBottomLeft;
-    private TextView _textViewBottomRight;
-    private TextView _textViewCentered;
-    private TextView _textViewTopLeft;
-    private TextView _textViewTopRight;
+    private CheckBox? _miMultilineCheckBox;
+    private CheckBox? _miWrapCheckBox;
+    private Shortcut? _siMultiline;
+    private Shortcut? _siWrap;
+    private TextView? _textViewBottomLeft;
+    private TextView? _textViewBottomRight;
+    private TextView? _textViewCentered;
+    private TextView? _textViewTopLeft;
+    private TextView? _textViewTopRight;
 
 
     public override void Main ()
     public override void Main ()
     {
     {
-        // Init
         Application.Init ();
         Application.Init ();
 
 
-        // Setup - Create a top-level application window and configure it.
-        Toplevel appWindow = new ();
+        Window appWindow = new ()
+        {
+            BorderStyle = LineStyle.None
+        };
 
 
         var width = 20;
         var width = 20;
         var text = " jamp jemp jimp jomp jump";
         var text = " jamp jemp jimp jomp jump";
 
 
-        var menu = new MenuBar
-        {
-            Menus =
-            [
-                new (
-                     "_File",
-                     new []
-                     {
-                         _miMultiline =
-                             new (
-                                  "_Multiline",
-                                  "",
-                                  () => Multiline ()
-                                 ) { CheckType = MenuItemCheckStyle.Checked },
-                         _miWrap = new (
-                                        "_Word Wrap",
-                                        "",
-                                        () => WordWrap ()
-                                       ) { CheckType = MenuItemCheckStyle.Checked },
-                         new ("_Quit", "", () => Quit ())
-                     }
-                    )
-            ]
-        };
-        appWindow.Add (menu);
+        // MenuBar
+        MenuBar menu = new ();
 
 
-        _textViewTopLeft = new()
+        _textViewTopLeft = new ()
         {
         {
-            Y = 1,
-            Width = width, Height = _height, Text = text
+            Y = Pos.Bottom (menu),
+            Width = width,
+            Height = _height,
+            Text = text
         };
         };
         _textViewTopLeft.DrawingContent += TextViewTopLeft_DrawContent;
         _textViewTopLeft.DrawingContent += TextViewTopLeft_DrawContent;
         appWindow.Add (_textViewTopLeft);
         appWindow.Add (_textViewTopLeft);
 
 
-        _textViewTopRight = new()
+        _textViewTopRight = new ()
         {
         {
-            X = Pos.AnchorEnd (width), Y = 1,
-            Width = width, Height = _height, Text = text
+            X = Pos.AnchorEnd (width),
+            Y = Pos.Bottom (menu),
+            Width = width,
+            Height = _height,
+            Text = text
         };
         };
         _textViewTopRight.DrawingContent += TextViewTopRight_DrawContent;
         _textViewTopRight.DrawingContent += TextViewTopRight_DrawContent;
         appWindow.Add (_textViewTopRight);
         appWindow.Add (_textViewTopRight);
 
 
-        _textViewBottomLeft = new()
+        _textViewBottomLeft = new ()
         {
         {
-            Y = Pos.AnchorEnd (_height), Width = width, Height = _height, Text = text
+            Y = Pos.AnchorEnd (_height),
+            Width = width,
+            Height = _height,
+            Text = text
         };
         };
         _textViewBottomLeft.DrawingContent += TextViewBottomLeft_DrawContent;
         _textViewBottomLeft.DrawingContent += TextViewBottomLeft_DrawContent;
         appWindow.Add (_textViewBottomLeft);
         appWindow.Add (_textViewBottomLeft);
 
 
-        _textViewBottomRight = new()
+        _textViewBottomRight = new ()
         {
         {
             X = Pos.AnchorEnd (width),
             X = Pos.AnchorEnd (width),
             Y = Pos.AnchorEnd (_height),
             Y = Pos.AnchorEnd (_height),
@@ -91,7 +78,7 @@ public class TextViewAutocompletePopup : Scenario
         _textViewBottomRight.DrawingContent += TextViewBottomRight_DrawContent;
         _textViewBottomRight.DrawingContent += TextViewBottomRight_DrawContent;
         appWindow.Add (_textViewBottomRight);
         appWindow.Add (_textViewBottomRight);
 
 
-        _textViewCentered = new()
+        _textViewCentered = new ()
         {
         {
             X = Pos.Center (),
             X = Pos.Center (),
             Y = Pos.Center (),
             Y = Pos.Center (),
@@ -102,73 +89,170 @@ public class TextViewAutocompletePopup : Scenario
         _textViewCentered.DrawingContent += TextViewCentered_DrawContent;
         _textViewCentered.DrawingContent += TextViewCentered_DrawContent;
         appWindow.Add (_textViewCentered);
         appWindow.Add (_textViewCentered);
 
 
-        _miMultiline.Checked = _textViewTopLeft.Multiline;
-        _miWrap.Checked = _textViewTopLeft.WordWrap;
+        // Setup menu checkboxes
+        _miMultilineCheckBox = new ()
+        {
+            Title = "_Multiline",
+            CheckedState = _textViewTopLeft.Multiline ? CheckState.Checked : CheckState.UnChecked
+        };
+        _miMultilineCheckBox.CheckedStateChanged += (s, e) => Multiline ();
+
+        _miWrapCheckBox = new ()
+        {
+            Title = "_Word Wrap",
+            CheckedState = _textViewTopLeft.WordWrap ? CheckState.Checked : CheckState.UnChecked
+        };
+        _miWrapCheckBox.CheckedStateChanged += (s, e) => WordWrap ();
 
 
-        var statusBar = new StatusBar (
-                                       new []
+        menu.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuItem
+                                       {
+                                           CommandView = _miMultilineCheckBox
+                                       },
+                                       new MenuItem
                                        {
                                        {
-                                           new (
-                                                Application.QuitKey,
-                                                "Quit",
-                                                () => Quit ()
-                                               ),
-                                           _siMultiline = new (Key.Empty, "", null),
-                                           _siWrap = new (Key.Empty, "", null)
+                                           CommandView = _miWrapCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Action = Quit
                                        }
                                        }
-                                      );
-        appWindow.Add (statusBar);
+                                   ]
+                                  )
+                 );
+
+        // StatusBar
+        _siMultiline = new (Key.Empty, "", null);
+        _siWrap = new (Key.Empty, "", null);
+
+        StatusBar statusBar = new (
+                                   [
+                                       new (
+                                            Application.QuitKey,
+                                            "Quit",
+                                            () => Quit ()
+                                           ),
+                                       _siMultiline,
+                                       _siWrap
+                                   ]
+                                  );
+
+        appWindow.Add (menu, statusBar);
 
 
         appWindow.SubViewLayout += Win_LayoutStarted;
         appWindow.SubViewLayout += Win_LayoutStarted;
 
 
-        // Run - Start the application.
         Application.Run (appWindow);
         Application.Run (appWindow);
-
         appWindow.Dispose ();
         appWindow.Dispose ();
-
-        // Shutdown - Calling Application.Shutdown is required.
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
     private void Multiline ()
     private void Multiline ()
     {
     {
-        _miMultiline.Checked = !_miMultiline.Checked;
+        if (_miMultilineCheckBox is null
+            || _textViewTopLeft is null
+            || _textViewTopRight is null
+            || _textViewBottomLeft is null
+            || _textViewBottomRight is null
+            || _textViewCentered is null)
+        {
+            return;
+        }
+
         SetMultilineStatusText ();
         SetMultilineStatusText ();
-        _textViewTopLeft.Multiline = (bool)_miMultiline.Checked;
-        _textViewTopRight.Multiline = (bool)_miMultiline.Checked;
-        _textViewBottomLeft.Multiline = (bool)_miMultiline.Checked;
-        _textViewBottomRight.Multiline = (bool)_miMultiline.Checked;
-        _textViewCentered.Multiline = (bool)_miMultiline.Checked;
+        _textViewTopLeft.Multiline = _miMultilineCheckBox.CheckedState == CheckState.Checked;
+        _textViewTopRight.Multiline = _miMultilineCheckBox.CheckedState == CheckState.Checked;
+        _textViewBottomLeft.Multiline = _miMultilineCheckBox.CheckedState == CheckState.Checked;
+        _textViewBottomRight.Multiline = _miMultilineCheckBox.CheckedState == CheckState.Checked;
+        _textViewCentered.Multiline = _miMultilineCheckBox.CheckedState == CheckState.Checked;
     }
     }
 
 
     private void Quit () { Application.RequestStop (); }
     private void Quit () { Application.RequestStop (); }
 
 
     private void SetAllSuggestions (TextView view)
     private void SetAllSuggestions (TextView view)
     {
     {
-        ((SingleWordSuggestionGenerator)view.Autocomplete.SuggestionGenerator).AllSuggestions = Regex
-                                                                                                .Matches (view.Text, "\\w+")
-                                                                                                .Select (s => s.Value)
-                                                                                                .Distinct ()
-                                                                                                .ToList ();
+        if (view.Autocomplete.SuggestionGenerator is SingleWordSuggestionGenerator generator)
+        {
+            generator.AllSuggestions = Regex
+                                       .Matches (view.Text, "\\w+")
+                                       .Select (s => s.Value)
+                                       .Distinct ()
+                                       .ToList ();
+        }
     }
     }
 
 
-    private void SetMultilineStatusText () { _siMultiline.Title = $"Multiline: {_miMultiline.Checked}"; }
+    private void SetMultilineStatusText ()
+    {
+        if (_siMultiline is { } && _miMultilineCheckBox is { })
+        {
+            _siMultiline.Title = $"Multiline: {_miMultilineCheckBox.CheckedState == CheckState.Checked}";
+        }
+    }
 
 
-    private void SetWrapStatusText () { _siWrap.Title = $"WordWrap: {_miWrap.Checked}"; }
-    private void TextViewBottomLeft_DrawContent (object sender, DrawEventArgs e) { SetAllSuggestions (_textViewBottomLeft); }
-    private void TextViewBottomRight_DrawContent (object sender, DrawEventArgs e) { SetAllSuggestions (_textViewBottomRight); }
-    private void TextViewCentered_DrawContent (object sender, DrawEventArgs e) { SetAllSuggestions (_textViewCentered); }
-    private void TextViewTopLeft_DrawContent (object sender, DrawEventArgs e) { SetAllSuggestions (_textViewTopLeft); }
-    private void TextViewTopRight_DrawContent (object sender, DrawEventArgs e) { SetAllSuggestions (_textViewTopRight); }
+    private void SetWrapStatusText ()
+    {
+        if (_siWrap is { } && _miWrapCheckBox is { })
+        {
+            _siWrap.Title = $"WordWrap: {_miWrapCheckBox.CheckedState == CheckState.Checked}";
+        }
+    }
+
+    private void TextViewBottomLeft_DrawContent (object? sender, DrawEventArgs e)
+    {
+        if (_textViewBottomLeft is { })
+        {
+            SetAllSuggestions (_textViewBottomLeft);
+        }
+    }
 
 
-    private void Win_LayoutStarted (object sender, LayoutEventArgs obj)
+    private void TextViewBottomRight_DrawContent (object? sender, DrawEventArgs e)
     {
     {
-        _miMultiline.Checked = _textViewTopLeft.Multiline;
-        _miWrap.Checked = _textViewTopLeft.WordWrap;
+        if (_textViewBottomRight is { })
+        {
+            SetAllSuggestions (_textViewBottomRight);
+        }
+    }
+
+    private void TextViewCentered_DrawContent (object? sender, DrawEventArgs e)
+    {
+        if (_textViewCentered is { })
+        {
+            SetAllSuggestions (_textViewCentered);
+        }
+    }
+
+    private void TextViewTopLeft_DrawContent (object? sender, DrawEventArgs e)
+    {
+        if (_textViewTopLeft is { })
+        {
+            SetAllSuggestions (_textViewTopLeft);
+        }
+    }
+
+    private void TextViewTopRight_DrawContent (object? sender, DrawEventArgs e)
+    {
+        if (_textViewTopRight is { })
+        {
+            SetAllSuggestions (_textViewTopRight);
+        }
+    }
+
+    private void Win_LayoutStarted (object? sender, LayoutEventArgs obj)
+    {
+        if (_textViewTopLeft is null || _miMultilineCheckBox is null || _miWrapCheckBox is null || _textViewBottomLeft is null || _textViewBottomRight is null)
+        {
+            return;
+        }
+
+        _miMultilineCheckBox.CheckedState = _textViewTopLeft.Multiline ? CheckState.Checked : CheckState.UnChecked;
+        _miWrapCheckBox.CheckedState = _textViewTopLeft.WordWrap ? CheckState.Checked : CheckState.UnChecked;
         SetMultilineStatusText ();
         SetMultilineStatusText ();
         SetWrapStatusText ();
         SetWrapStatusText ();
 
 
-        if (_miMultiline.Checked == true)
+        if (_miMultilineCheckBox.CheckedState == CheckState.Checked)
         {
         {
             _height = 10;
             _height = 10;
         }
         }
@@ -182,13 +266,22 @@ public class TextViewAutocompletePopup : Scenario
 
 
     private void WordWrap ()
     private void WordWrap ()
     {
     {
-        _miWrap.Checked = !_miWrap.Checked;
-        _textViewTopLeft.WordWrap = (bool)_miWrap.Checked;
-        _textViewTopRight.WordWrap = (bool)_miWrap.Checked;
-        _textViewBottomLeft.WordWrap = (bool)_miWrap.Checked;
-        _textViewBottomRight.WordWrap = (bool)_miWrap.Checked;
-        _textViewCentered.WordWrap = (bool)_miWrap.Checked;
-        _miWrap.Checked = _textViewTopLeft.WordWrap;
+        if (_miWrapCheckBox is null
+            || _textViewTopLeft is null
+            || _textViewTopRight is null
+            || _textViewBottomLeft is null
+            || _textViewBottomRight is null
+            || _textViewCentered is null)
+        {
+            return;
+        }
+
+        _textViewTopLeft.WordWrap = _miWrapCheckBox.CheckedState == CheckState.Checked;
+        _textViewTopRight.WordWrap = _miWrapCheckBox.CheckedState == CheckState.Checked;
+        _textViewBottomLeft.WordWrap = _miWrapCheckBox.CheckedState == CheckState.Checked;
+        _textViewBottomRight.WordWrap = _miWrapCheckBox.CheckedState == CheckState.Checked;
+        _textViewCentered.WordWrap = _miWrapCheckBox.CheckedState == CheckState.Checked;
+        _miWrapCheckBox.CheckedState = _textViewTopLeft.WordWrap ? CheckState.Checked : CheckState.UnChecked;
         SetWrapStatusText ();
         SetWrapStatusText ();
     }
     }
 }
 }

+ 1 - 1
Examples/UICatalog/Scenarios/Themes.cs

@@ -129,7 +129,7 @@ public sealed class Themes : Scenario
                                           {
                                           {
                                               if (_view is { })
                                               if (_view is { })
                                               {
                                               {
-                                                  Application.Current!.SchemeName = args.NewValue;
+                                                  Application.TopRunnableView!.SchemeName = args.NewValue;
 
 
                                                   if (_view.HasScheme)
                                                   if (_view.HasScheme)
                                                   {
                                                   {

+ 4 - 4
Examples/UICatalog/Scenarios/Threading.cs

@@ -75,7 +75,7 @@ public class Threading : Scenario
             Y = Pos.Y (_btnActionCancel) + 6,
             Y = Pos.Y (_btnActionCancel) + 6,
             Width = 10,
             Width = 10,
             Height = 10,
             Height = 10,
-            SchemeName = "TopLevel"
+            SchemeName = "Runnable"
         };
         };
 
 
         win.Add (new Label { X = Pos.Right (_itemsList) + 10, Y = Pos.Y (_btnActionCancel) + 4, Text = "Task Logs:" });
         win.Add (new Label { X = Pos.Right (_itemsList) + 10, Y = Pos.Y (_btnActionCancel) + 4, Text = "Task Logs:" });
@@ -86,7 +86,7 @@ public class Threading : Scenario
             Y = Pos.Y (_itemsList),
             Y = Pos.Y (_itemsList),
             Width = 50,
             Width = 50,
             Height = Dim.Fill (),
             Height = Dim.Fill (),
-            SchemeName = "TopLevel",
+            SchemeName = "Runnable",
             Source = new ListWrapper<string> (_log)
             Source = new ListWrapper<string> (_log)
         };
         };
 
 
@@ -162,10 +162,10 @@ public class Threading : Scenario
         void Win_Loaded (object sender, EventArgs args)
         void Win_Loaded (object sender, EventArgs args)
         {
         {
             _btnActionCancel.SetFocus ();
             _btnActionCancel.SetFocus ();
-            win.Loaded -= Win_Loaded;
+            win.IsModalChanged -= Win_Loaded;
         }
         }
 
 
-        win.Loaded += Win_Loaded;
+        win.IsModalChanged += Win_Loaded;
 
 
         Application.Run (win);
         Application.Run (win);
         win.Dispose ();
         win.Dispose ();

+ 2 - 2
Examples/UICatalog/Scenarios/Transparent.cs

@@ -46,7 +46,7 @@ public sealed class Transparent : Scenario
         };
         };
         appButton.Accepting += (sender, args) =>
         appButton.Accepting += (sender, args) =>
                                {
                                {
-                                   MessageBox.Query ("AppButton", "Transparency is cool!", "_Ok");
+                                   MessageBox.Query ((sender as View)?.App, "AppButton", "Transparency is cool!", "_Ok");
                                    args.Handled = true;
                                    args.Handled = true;
                                };
                                };
         appWindow.Add (appButton);
         appWindow.Add (appButton);
@@ -106,7 +106,7 @@ public sealed class Transparent : Scenario
             };
             };
             button.Accepting += (sender, args) =>
             button.Accepting += (sender, args) =>
                                 {
                                 {
-                                    MessageBox.Query ("Clicked!", "Button in Transparent View", "_Ok");
+                                    MessageBox.Query (App, "Clicked!", "Button in Transparent View", "_Ok");
                                     args.Handled = true;
                                     args.Handled = true;
                                 };
                                 };
             //button.Visible = false;
             //button.Visible = false;

+ 123 - 81
Examples/UICatalog/Scenarios/TreeUseCases.cs

@@ -1,3 +1,5 @@
+#nullable enable
+
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 
 
@@ -8,76 +10,96 @@ namespace UICatalog.Scenarios;
 [ScenarioCategory ("TreeView")]
 [ScenarioCategory ("TreeView")]
 public class TreeUseCases : Scenario
 public class TreeUseCases : Scenario
 {
 {
-    private View _currentTree;
+    private View? _currentTree;
 
 
     public override void Main ()
     public override void Main ()
     {
     {
-        // Init
         Application.Init ();
         Application.Init ();
 
 
-        // Setup - Create a top-level application window and configure it.
-        Toplevel appWindow = new ();
-
-        var menu = new MenuBar
-        {
-            Menus =
+        Window appWindow = new ();
+
+        // MenuBar
+        MenuBar menu = new ();
+
+        menu.Add (
+            new MenuBarItem (
+                "_File",
+                [
+                    new MenuItem
+                    {
+                        Title = "_Quit",
+                        Action = Quit
+                    }
+                ]
+            )
+        );
+
+        menu.Add (
+            new MenuBarItem (
+                "_Scenarios",
+                [
+                    new MenuItem
+                    {
+                        Title = "_Simple Nodes",
+                        Action = LoadSimpleNodes
+                    },
+                    new MenuItem
+                    {
+                        Title = "_Rooms",
+                        Action = LoadRooms
+                    },
+                    new MenuItem
+                    {
+                        Title = "_Armies With Builder",
+                        Action = () => LoadArmies (false)
+                    },
+                    new MenuItem
+                    {
+                        Title = "_Armies With Delegate",
+                        Action = () => LoadArmies (true)
+                    }
+                ]
+            )
+        );
+
+        // StatusBar
+        StatusBar statusBar = new (
             [
             [
-                new MenuBarItem ("_File", new MenuItem [] { new ("_Quit", "", () => Quit ()) }),
-                new MenuBarItem (
-                                 "_Scenarios",
-                                 new MenuItem []
-                                 {
-                                     new (
-                                          "_Simple Nodes",
-                                          "",
-                                          () => LoadSimpleNodes ()
-                                         ),
-                                     new ("_Rooms", "", () => LoadRooms ()),
-                                     new (
-                                          "_Armies With Builder",
-                                          "",
-                                          () => LoadArmies (false)
-                                         ),
-                                     new (
-                                          "_Armies With Delegate",
-                                          "",
-                                          () => LoadArmies (true)
-                                         )
-                                 }
-                                )
+                new (Application.QuitKey, "Quit", Quit)
             ]
             ]
-        };
-
-        appWindow.Add (menu);
+        );
 
 
-        var statusBar = new StatusBar ([new (Application.QuitKey, "Quit", Quit)]);
+        appWindow.Add (menu, statusBar);
 
 
-        appWindow.Add (statusBar);
-
-        appWindow.Ready += (sender, args) =>
-                                        // Start with the most basic use case
-                                        LoadSimpleNodes ();
+        appWindow.IsModalChanged += (sender, args) =>
+        {
+            if (args.Value)
+            {
+                // Start with the most basic use case
+                LoadSimpleNodes ();
+            }
+        };
 
 
-        // Run - Start the application.
         Application.Run (appWindow);
         Application.Run (appWindow);
         appWindow.Dispose ();
         appWindow.Dispose ();
-
-        // Shutdown - Calling Application.Shutdown is required.
         Application.Shutdown ();
         Application.Shutdown ();
-
     }
     }
 
 
     private void LoadArmies (bool useDelegate)
     private void LoadArmies (bool useDelegate)
     {
     {
-        var army1 = new Army
+        Army army1 = new ()
         {
         {
             Designation = "3rd Infantry",
             Designation = "3rd Infantry",
-            Units = new List<Unit> { new () { Name = "Orc" }, new () { Name = "Troll" }, new () { Name = "Goblin" } }
+            Units = [new () { Name = "Orc" }, new () { Name = "Troll" }, new () { Name = "Goblin" }]
         };
         };
 
 
-        if (_currentTree != null)
+        if (_currentTree is { })
         {
         {
-            Application.Current.Remove (_currentTree);
+            if (Application.TopRunnableView is { })
+            {
+                Application.TopRunnableView.Remove (_currentTree);
+            }
+
             _currentTree.Dispose ();
             _currentTree.Dispose ();
         }
         }
 
 
@@ -86,18 +108,21 @@ public class TreeUseCases : Scenario
         if (useDelegate)
         if (useDelegate)
         {
         {
             tree.TreeBuilder = new DelegateTreeBuilder<GameObject> (
             tree.TreeBuilder = new DelegateTreeBuilder<GameObject> (
-                                                                    o =>
-                                                                        o is Army a
-                                                                            ? a.Units
-                                                                            : Enumerable.Empty<GameObject> ()
-                                                                   );
+                o =>
+                    o is Army a && a.Units is { }
+                        ? a.Units
+                        : Enumerable.Empty<GameObject> ()
+            );
         }
         }
         else
         else
         {
         {
             tree.TreeBuilder = new GameObjectTreeBuilder ();
             tree.TreeBuilder = new GameObjectTreeBuilder ();
         }
         }
 
 
-        Application.Current.Add (tree);
+        if (Application.TopRunnableView is { })
+        {
+            Application.TopRunnableView.Add (tree);
+        }
 
 
         tree.AddObject (army1);
         tree.AddObject (army1);
 
 
@@ -106,24 +131,33 @@ public class TreeUseCases : Scenario
 
 
     private void LoadRooms ()
     private void LoadRooms ()
     {
     {
-        var myHouse = new House
+        House myHouse = new ()
         {
         {
             Address = "23 Nowhere Street",
             Address = "23 Nowhere Street",
-            Rooms = new List<Room>
-            {
-                new () { Name = "Ballroom" }, new () { Name = "Bedroom 1" }, new () { Name = "Bedroom 2" }
-            }
+            Rooms =
+            [
+                new () { Name = "Ballroom" },
+                new () { Name = "Bedroom 1" },
+                new () { Name = "Bedroom 2" }
+            ]
         };
         };
 
 
-        if (_currentTree != null)
+        if (_currentTree is { })
         {
         {
-            Application.Current.Remove (_currentTree);
+            if (Application.TopRunnableView is { })
+            {
+                Application.TopRunnableView.Remove (_currentTree);
+            }
+
             _currentTree.Dispose ();
             _currentTree.Dispose ();
         }
         }
 
 
-        var tree = new TreeView { X = 0, Y = 1, Width = Dim.Fill(), Height = Dim.Fill (1) };
+        TreeView tree = new () { X = 0, Y = 1, Width = Dim.Fill (), Height = Dim.Fill (1) };
 
 
-        Application.Current.Add (tree);
+        if (Application.TopRunnableView is { })
+        {
+            Application.TopRunnableView.Add (tree);
+        }
 
 
         tree.AddObject (myHouse);
         tree.AddObject (myHouse);
 
 
@@ -132,21 +166,28 @@ public class TreeUseCases : Scenario
 
 
     private void LoadSimpleNodes ()
     private void LoadSimpleNodes ()
     {
     {
-        if (_currentTree != null)
+        if (_currentTree is { })
         {
         {
-            Application.Current.Remove (_currentTree);
+            if (Application.TopRunnableView is { })
+            {
+                Application.TopRunnableView.Remove (_currentTree);
+            }
+
             _currentTree.Dispose ();
             _currentTree.Dispose ();
         }
         }
 
 
-        var tree = new TreeView { X = 0, Y = 1, Width = Dim.Fill (), Height = Dim.Fill (1) };
+        TreeView tree = new () { X = 0, Y = 1, Width = Dim.Fill (), Height = Dim.Fill (1) };
 
 
-        Application.Current.Add (tree);
+        if (Application.TopRunnableView is { })
+        {
+            Application.TopRunnableView.Add (tree);
+        }
 
 
-        var root1 = new TreeNode ("Root1");
+        TreeNode root1 = new ("Root1");
         root1.Children.Add (new TreeNode ("Child1.1"));
         root1.Children.Add (new TreeNode ("Child1.1"));
         root1.Children.Add (new TreeNode ("Child1.2"));
         root1.Children.Add (new TreeNode ("Child1.2"));
 
 
-        var root2 = new TreeNode ("Root2");
+        TreeNode root2 = new ("Root2");
         root2.Children.Add (new TreeNode ("Child2.1"));
         root2.Children.Add (new TreeNode ("Child2.1"));
         root2.Children.Add (new TreeNode ("Child2.2"));
         root2.Children.Add (new TreeNode ("Child2.2"));
 
 
@@ -156,17 +197,21 @@ public class TreeUseCases : Scenario
         _currentTree = tree;
         _currentTree = tree;
     }
     }
 
 
-    private void Quit () { Application.RequestStop (); }
+    private void Quit ()
+    {
+        Application.RequestStop ();
+    }
 
 
     private class Army : GameObject
     private class Army : GameObject
     {
     {
-        public string Designation { get; set; }
-        public List<Unit> Units { get; set; }
+        public string Designation { get; set; } = string.Empty;
+        public List<Unit> Units { get; set; } = [];
         public override string ToString () { return Designation; }
         public override string ToString () { return Designation; }
     }
     }
 
 
     private abstract class GameObject
     private abstract class GameObject
-    { }
+    {
+    }
 
 
     private class GameObjectTreeBuilder : ITreeBuilder<GameObject>
     private class GameObjectTreeBuilder : ITreeBuilder<GameObject>
     {
     {
@@ -175,7 +220,7 @@ public class TreeUseCases : Scenario
 
 
         public IEnumerable<GameObject> GetChildren (GameObject model)
         public IEnumerable<GameObject> GetChildren (GameObject model)
         {
         {
-            if (model is Army a)
+            if (model is Army a && a.Units is { })
             {
             {
                 return a.Units;
                 return a.Units;
             }
             }
@@ -184,15 +229,12 @@ public class TreeUseCases : Scenario
         }
         }
     }
     }
 
 
-    // Your data class
     private class House : TreeNode
     private class House : TreeNode
     {
     {
-        // Your properties
-        public string Address { get; set; }
+        public string Address { get; set; } = string.Empty;
 
 
-        // ITreeNode member:
         public override IList<ITreeNode> Children => Rooms.Cast<ITreeNode> ().ToList ();
         public override IList<ITreeNode> Children => Rooms.Cast<ITreeNode> ().ToList ();
-        public List<Room> Rooms { get; set; }
+        public List<Room> Rooms { get; set; } = [];
 
 
         public override string Text
         public override string Text
         {
         {
@@ -203,7 +245,7 @@ public class TreeUseCases : Scenario
 
 
     private class Room : TreeNode
     private class Room : TreeNode
     {
     {
-        public string Name { get; set; }
+        public string Name { get; set; } = string.Empty;
 
 
         public override string Text
         public override string Text
         {
         {
@@ -214,7 +256,7 @@ public class TreeUseCases : Scenario
 
 
     private class Unit : GameObject
     private class Unit : GameObject
     {
     {
-        public string Name { get; set; }
+        public string Name { get; set; } = string.Empty;
         public override string ToString () { return Name; }
         public override string ToString () { return Name; }
     }
     }
 }
 }

+ 340 - 249
Examples/UICatalog/Scenarios/TreeViewFileSystem.cs

@@ -1,3 +1,5 @@
+#nullable enable
+
 using System.IO.Abstractions;
 using System.IO.Abstractions;
 using System.Text;
 using System.Text;
 
 
@@ -10,180 +12,51 @@ namespace UICatalog.Scenarios;
 public class TreeViewFileSystem : Scenario
 public class TreeViewFileSystem : Scenario
 {
 {
     private readonly FileSystemIconProvider _iconProvider = new ();
     private readonly FileSystemIconProvider _iconProvider = new ();
-    private DetailsFrame _detailsFrame;
-    private MenuItem _miArrowSymbols;
-    private MenuItem _miBasicIcons;
-    private MenuItem _miColoredSymbols;
-    private MenuItem _miCursor;
-    private MenuItem _miCustomColors;
-    private MenuItem _miFullPaths;
-    private MenuItem _miHighlightModelTextOnly;
-    private MenuItem _miInvertSymbols;
-    private MenuItem _miLeaveLastRow;
-    private MenuItem _miMultiSelect;
-    private MenuItem _miNerdIcons;
-    private MenuItem _miNoSymbols;
-    private MenuItem _miPlusMinus;
-    private MenuItem _miShowLines;
-    private MenuItem _miUnicodeIcons;
+    private DetailsFrame? _detailsFrame;
+    private CheckBox? _miArrowSymbolsCheckBox;
+    private CheckBox? _miBasicIconsCheckBox;
+    private CheckBox? _miColoredSymbolsCheckBox;
+    private CheckBox? _miCursorCheckBox;
+    private CheckBox? _miCustomColorsCheckBox;
+    private CheckBox? _miFullPathsCheckBox;
+    private CheckBox? _miHighlightModelTextOnlyCheckBox;
+    private CheckBox? _miInvertSymbolsCheckBox;
+    private CheckBox? _miLeaveLastRowCheckBox;
+    private CheckBox? _miMultiSelectCheckBox;
+    private CheckBox? _miNerdIconsCheckBox;
+    private CheckBox? _miNoSymbolsCheckBox;
+    private CheckBox? _miPlusMinusCheckBox;
+    private CheckBox? _miShowLinesCheckBox;
+    private CheckBox? _miUnicodeIconsCheckBox;
 
 
     /// <summary>A tree view where nodes are files and folders</summary>
     /// <summary>A tree view where nodes are files and folders</summary>
-    private TreeView<IFileSystemInfo> _treeViewFiles;
+    private TreeView<IFileSystemInfo>? _treeViewFiles;
 
 
     public override void Main ()
     public override void Main ()
     {
     {
         Application.Init ();
         Application.Init ();
 
 
-        var win = new Window
+        Window win = new ()
         {
         {
             Title = GetName (),
             Title = GetName (),
             Y = 1, // menu
             Y = 1, // menu
             Height = Dim.Fill ()
             Height = Dim.Fill ()
         };
         };
-        var top = new Toplevel ();
-
-        var menu = new MenuBar
-        {
-            Menus =
-            [
-                new (
-                     "_File",
-                     new MenuItem []
-                     {
-                         new (
-                              "_Quit",
-                              $"{Application.QuitKey}",
-                              () => Quit ()
-                             )
-                     }
-                    ),
-                new (
-                     "_View",
-                     new []
-                     {
-                         _miFullPaths =
-                             new ("_Full Paths", "", () => SetFullName ())
-                             {
-                                 Checked = false, CheckType = MenuItemCheckStyle.Checked
-                             },
-                         _miMultiSelect = new (
-                                               "_Multi Select",
-                                               "",
-                                               () => SetMultiSelect ()
-                                              )
-                         {
-                             Checked = true,
-                             CheckType = MenuItemCheckStyle
-                                 .Checked
-                         }
-                     }
-                    ),
-                new (
-                     "_Style",
-                     new []
-                     {
-                         _miShowLines =
-                             new ("_Show Lines", "", () => ShowLines ())
-                             {
-                                 Checked = true, CheckType = MenuItemCheckStyle.Checked
-                             },
-                         null /*separator*/,
-                         _miPlusMinus =
-                             new (
-                                  "_Plus Minus Symbols",
-                                  "+ -",
-                                  () => SetExpandableSymbols (
-                                                              (Rune)'+',
-                                                              (Rune)'-'
-                                                             )
-                                 ) { Checked = true, CheckType = MenuItemCheckStyle.Radio },
-                         _miArrowSymbols =
-                             new (
-                                  "_Arrow Symbols",
-                                  "> v",
-                                  () => SetExpandableSymbols (
-                                                              (Rune)'>',
-                                                              (Rune)'v'
-                                                             )
-                                 ) { Checked = false, CheckType = MenuItemCheckStyle.Radio },
-                         _miNoSymbols =
-                             new (
-                                  "_No Symbols",
-                                  "",
-                                  () => SetExpandableSymbols (
-                                                              default (Rune),
-                                                              null
-                                                             )
-                                 ) { Checked = false, CheckType = MenuItemCheckStyle.Radio },
-                         null /*separator*/,
-                         _miColoredSymbols =
-                             new (
-                                  "_Colored Symbols",
-                                  "",
-                                  () => ShowColoredExpandableSymbols ()
-                                 ) { Checked = false, CheckType = MenuItemCheckStyle.Checked },
-                         _miInvertSymbols =
-                             new (
-                                  "_Invert Symbols",
-                                  "",
-                                  () => InvertExpandableSymbols ()
-                                 ) { Checked = false, CheckType = MenuItemCheckStyle.Checked },
-                         null /*separator*/,
-                         _miBasicIcons =
-                             new ("_Basic Icons", null, SetNoIcons)
-                             {
-                                 Checked = false, CheckType = MenuItemCheckStyle.Radio
-                             },
-                         _miUnicodeIcons =
-                             new ("_Unicode Icons", null, SetUnicodeIcons)
-                             {
-                                 Checked = false, CheckType = MenuItemCheckStyle.Radio
-                             },
-                         _miNerdIcons =
-                             new ("_Nerd Icons", null, SetNerdIcons)
-                             {
-                                 Checked = false, CheckType = MenuItemCheckStyle.Radio
-                             },
-                         null /*separator*/,
-                         _miLeaveLastRow =
-                             new (
-                                  "_Leave Last Row",
-                                  "",
-                                  () => SetLeaveLastRow ()
-                                 ) { Checked = true, CheckType = MenuItemCheckStyle.Checked },
-                         _miHighlightModelTextOnly =
-                             new (
-                                  "_Highlight Model Text Only",
-                                  "",
-                                  () => SetCheckHighlightModelTextOnly ()
-                                 ) { Checked = false, CheckType = MenuItemCheckStyle.Checked },
-                         null /*separator*/,
-                         _miCustomColors =
-                             new (
-                                  "C_ustom Colors Hidden Files",
-                                  "Yellow/Red",
-                                  () => SetCustomColors ()
-                                 ) { Checked = false, CheckType = MenuItemCheckStyle.Checked },
-                         null /*separator*/,
-                         _miCursor = new (
-                                          "Curs_or (MultiSelect only)",
-                                          "",
-                                          () => SetCursor ()
-                                         ) { Checked = false, CheckType = MenuItemCheckStyle.Checked }
-                     }
-                    )
-            ]
-        };
-        top.Add (menu);
 
 
-        _treeViewFiles = new () { X = 0, Y = 0, Width = Dim.Percent (50), Height = Dim.Fill () };
+        // MenuBar
+        MenuBar menu = new ();
+
+        _treeViewFiles = new () { X = 0, Y = Pos.Bottom (menu), Width = Dim.Percent (50), Height = Dim.Fill () };
         _treeViewFiles.DrawLine += TreeViewFiles_DrawLine;
         _treeViewFiles.DrawLine += TreeViewFiles_DrawLine;
 
 
         _treeViewFiles.VerticalScrollBar.AutoShow = false;
         _treeViewFiles.VerticalScrollBar.AutoShow = false;
 
 
         _detailsFrame = new (_iconProvider)
         _detailsFrame = new (_iconProvider)
         {
         {
-            X = Pos.Right (_treeViewFiles), Y = 0, Width = Dim.Fill (), Height = Dim.Fill ()
+            X = Pos.Right (_treeViewFiles),
+            Y = Pos.Top (_treeViewFiles),
+            Width = Dim.Fill (),
+            Height = Dim.Fill ()
         };
         };
 
 
         win.Add (_detailsFrame);
         win.Add (_detailsFrame);
@@ -193,29 +66,214 @@ public class TreeViewFileSystem : Scenario
 
 
         SetupFileTree ();
         SetupFileTree ();
 
 
-        win.Add (_treeViewFiles);
-        top.Add (win);
+        // Setup menu checkboxes
+        _miFullPathsCheckBox = new ()
+        {
+            Title = "_Full Paths"
+        };
+        _miFullPathsCheckBox.CheckedStateChanged += (s, e) => SetFullName ();
+
+        _miMultiSelectCheckBox = new ()
+        {
+            Title = "_Multi Select",
+            CheckedState = CheckState.Checked
+        };
+        _miMultiSelectCheckBox.CheckedStateChanged += (s, e) => SetMultiSelect ();
+
+        _miShowLinesCheckBox = new ()
+        {
+            Title = "_Show Lines",
+            CheckedState = CheckState.Checked
+        };
+        _miShowLinesCheckBox.CheckedStateChanged += (s, e) => ShowLines ();
+
+        _miPlusMinusCheckBox = new ()
+        {
+            Title = "_Plus Minus Symbols",
+            CheckedState = CheckState.Checked
+        };
+        _miPlusMinusCheckBox.CheckedStateChanged += (s, e) => SetExpandableSymbols ((Rune)'+', (Rune)'-');
+
+        _miArrowSymbolsCheckBox = new ()
+        {
+            Title = "_Arrow Symbols"
+        };
+        _miArrowSymbolsCheckBox.CheckedStateChanged += (s, e) => SetExpandableSymbols ((Rune)'>', (Rune)'v');
+
+        _miNoSymbolsCheckBox = new ()
+        {
+            Title = "_No Symbols"
+        };
+        _miNoSymbolsCheckBox.CheckedStateChanged += (s, e) => SetExpandableSymbols (default (Rune), null);
+
+        _miColoredSymbolsCheckBox = new ()
+        {
+            Title = "_Colored Symbols"
+        };
+        _miColoredSymbolsCheckBox.CheckedStateChanged += (s, e) => ShowColoredExpandableSymbols ();
+
+        _miInvertSymbolsCheckBox = new ()
+        {
+            Title = "_Invert Symbols"
+        };
+        _miInvertSymbolsCheckBox.CheckedStateChanged += (s, e) => InvertExpandableSymbols ();
+
+        _miBasicIconsCheckBox = new ()
+        {
+            Title = "_Basic Icons"
+        };
+        _miBasicIconsCheckBox.CheckedStateChanged += (s, e) => SetNoIcons ();
+
+        _miUnicodeIconsCheckBox = new ()
+        {
+            Title = "_Unicode Icons"
+        };
+        _miUnicodeIconsCheckBox.CheckedStateChanged += (s, e) => SetUnicodeIcons ();
+
+        _miNerdIconsCheckBox = new ()
+        {
+            Title = "_Nerd Icons"
+        };
+        _miNerdIconsCheckBox.CheckedStateChanged += (s, e) => SetNerdIcons ();
+
+        _miLeaveLastRowCheckBox = new ()
+        {
+            Title = "_Leave Last Row",
+            CheckedState = CheckState.Checked
+        };
+        _miLeaveLastRowCheckBox.CheckedStateChanged += (s, e) => SetLeaveLastRow ();
+
+        _miHighlightModelTextOnlyCheckBox = new ()
+        {
+            Title = "_Highlight Model Text Only"
+        };
+        _miHighlightModelTextOnlyCheckBox.CheckedStateChanged += (s, e) => SetCheckHighlightModelTextOnly ();
+
+        _miCustomColorsCheckBox = new ()
+        {
+            Title = "C_ustom Colors Hidden Files"
+        };
+        _miCustomColorsCheckBox.CheckedStateChanged += (s, e) => SetCustomColors ();
+
+        _miCursorCheckBox = new ()
+        {
+            Title = "Curs_or (MultiSelect only)"
+        };
+        _miCursorCheckBox.CheckedStateChanged += (s, e) => SetCursor ();
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_Quit",
+                                           Key = Application.QuitKey,
+                                           Action = Quit
+                                       }
+                                   ]
+                                  )
+                 );
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_View",
+                                   [
+                                       new MenuItem
+                                       {
+                                           CommandView = _miFullPathsCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miMultiSelectCheckBox
+                                       }
+                                   ]
+                                  )
+                 );
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_Style",
+                                   [
+                                       new MenuItem
+                                       {
+                                           CommandView = _miShowLinesCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miPlusMinusCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miArrowSymbolsCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miNoSymbolsCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miColoredSymbolsCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miInvertSymbolsCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miBasicIconsCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miUnicodeIconsCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miNerdIconsCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miLeaveLastRowCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miHighlightModelTextOnlyCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miCustomColorsCheckBox
+                                       },
+                                       new MenuItem
+                                       {
+                                           CommandView = _miCursorCheckBox
+                                       }
+                                   ]
+                                  )
+                 );
+
+        win.Add (menu, _treeViewFiles);
         _treeViewFiles.GoToFirst ();
         _treeViewFiles.GoToFirst ();
         _treeViewFiles.Expand ();
         _treeViewFiles.Expand ();
 
 
-        //SetupScrollBar ();
-
         _treeViewFiles.SetFocus ();
         _treeViewFiles.SetFocus ();
 
 
         UpdateIconCheckedness ();
         UpdateIconCheckedness ();
 
 
-        Application.Run (top);
-        top.Dispose ();
+        Application.Run (win);
+        win.Dispose ();
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 
 
-    private string AspectGetter (IFileSystemInfo f) { return (_iconProvider.GetIconWithOptionalSpace (f) + f.Name).Trim (); }
+    private string AspectGetter (IFileSystemInfo f) => (_iconProvider.GetIconWithOptionalSpace (f) + f.Name).Trim ();
 
 
     private void InvertExpandableSymbols ()
     private void InvertExpandableSymbols ()
     {
     {
-        _miInvertSymbols.Checked = !_miInvertSymbols.Checked;
+        if (_treeViewFiles is null || _miInvertSymbolsCheckBox is null)
+        {
+            return;
+        }
 
 
-        _treeViewFiles.Style.InvertExpandSymbolColors = (bool)_miInvertSymbols.Checked;
+        _treeViewFiles.Style.InvertExpandSymbolColors = _miInvertSymbolsCheckBox.CheckedState == CheckState.Checked;
         _treeViewFiles.SetNeedsDraw ();
         _treeViewFiles.SetNeedsDraw ();
     }
     }
 
 
@@ -223,24 +281,34 @@ public class TreeViewFileSystem : Scenario
 
 
     private void SetCheckHighlightModelTextOnly ()
     private void SetCheckHighlightModelTextOnly ()
     {
     {
-        _treeViewFiles.Style.HighlightModelTextOnly = !_treeViewFiles.Style.HighlightModelTextOnly;
-        _miHighlightModelTextOnly.Checked = _treeViewFiles.Style.HighlightModelTextOnly;
+        if (_treeViewFiles is null || _miHighlightModelTextOnlyCheckBox is null)
+        {
+            return;
+        }
+
+        _treeViewFiles.Style.HighlightModelTextOnly = _miHighlightModelTextOnlyCheckBox.CheckedState == CheckState.Checked;
         _treeViewFiles.SetNeedsDraw ();
         _treeViewFiles.SetNeedsDraw ();
     }
     }
 
 
     private void SetCursor ()
     private void SetCursor ()
     {
     {
-        _miCursor.Checked = !_miCursor.Checked;
+        if (_treeViewFiles is null || _miCursorCheckBox is null)
+        {
+            return;
+        }
 
 
         _treeViewFiles.CursorVisibility =
         _treeViewFiles.CursorVisibility =
-            _miCursor.Checked == true ? CursorVisibility.Default : CursorVisibility.Invisible;
+            _miCursorCheckBox.CheckedState == CheckState.Checked ? CursorVisibility.Default : CursorVisibility.Invisible;
     }
     }
 
 
     private void SetCustomColors ()
     private void SetCustomColors ()
     {
     {
-        _miCustomColors.Checked = !_miCustomColors.Checked;
+        if (_treeViewFiles is null || _miCustomColorsCheckBox is null)
+        {
+            return;
+        }
 
 
-        if (_miCustomColors.Checked == true)
+        if (_miCustomColorsCheckBox.CheckedState == CheckState.Checked)
         {
         {
             _treeViewFiles.ColorGetter = m =>
             _treeViewFiles.ColorGetter = m =>
                                          {
                                          {
@@ -257,8 +325,6 @@ public class TreeViewFileSystem : Scenario
                                                                    _treeViewFiles.GetAttributeForRole (VisualRole.Normal).Background
                                                                    _treeViewFiles.GetAttributeForRole (VisualRole.Normal).Background
                                                                   )
                                                                   )
                                                  };
                                                  };
-
-                                                 ;
                                              }
                                              }
 
 
                                              if (m is IFileInfo && m.Attributes.HasFlag (FileAttributes.Hidden))
                                              if (m is IFileInfo && m.Attributes.HasFlag (FileAttributes.Hidden))
@@ -274,8 +340,6 @@ public class TreeViewFileSystem : Scenario
                                                                    _treeViewFiles.GetAttributeForRole (VisualRole.Normal).Background
                                                                    _treeViewFiles.GetAttributeForRole (VisualRole.Normal).Background
                                                                   )
                                                                   )
                                                  };
                                                  };
-
-                                                 ;
                                              }
                                              }
 
 
                                              return null;
                                              return null;
@@ -291,9 +355,25 @@ public class TreeViewFileSystem : Scenario
 
 
     private void SetExpandableSymbols (Rune expand, Rune? collapse)
     private void SetExpandableSymbols (Rune expand, Rune? collapse)
     {
     {
-        _miPlusMinus.Checked = expand.Value == '+';
-        _miArrowSymbols.Checked = expand.Value == '>';
-        _miNoSymbols.Checked = expand.Value == default (int);
+        if (_treeViewFiles is null)
+        {
+            return;
+        }
+
+        if (_miPlusMinusCheckBox is { })
+        {
+            _miPlusMinusCheckBox.CheckedState = expand.Value == '+' ? CheckState.Checked : CheckState.UnChecked;
+        }
+
+        if (_miArrowSymbolsCheckBox is { })
+        {
+            _miArrowSymbolsCheckBox.CheckedState = expand.Value == '>' ? CheckState.Checked : CheckState.UnChecked;
+        }
+
+        if (_miNoSymbolsCheckBox is { })
+        {
+            _miNoSymbolsCheckBox.CheckedState = expand.Value == default (int) ? CheckState.Checked : CheckState.UnChecked;
+        }
 
 
         _treeViewFiles.Style.ExpandableSymbol = expand;
         _treeViewFiles.Style.ExpandableSymbol = expand;
         _treeViewFiles.Style.CollapseableSymbol = collapse;
         _treeViewFiles.Style.CollapseableSymbol = collapse;
@@ -302,9 +382,12 @@ public class TreeViewFileSystem : Scenario
 
 
     private void SetFullName ()
     private void SetFullName ()
     {
     {
-        _miFullPaths.Checked = !_miFullPaths.Checked;
+        if (_treeViewFiles is null || _miFullPathsCheckBox is null)
+        {
+            return;
+        }
 
 
-        if (_miFullPaths.Checked == true)
+        if (_miFullPathsCheckBox.CheckedState == CheckState.Checked)
         {
         {
             _treeViewFiles.AspectGetter = f => f.FullName;
             _treeViewFiles.AspectGetter = f => f.FullName;
         }
         }
@@ -318,14 +401,22 @@ public class TreeViewFileSystem : Scenario
 
 
     private void SetLeaveLastRow ()
     private void SetLeaveLastRow ()
     {
     {
-        _miLeaveLastRow.Checked = !_miLeaveLastRow.Checked;
-        _treeViewFiles.Style.LeaveLastRow = (bool)_miLeaveLastRow.Checked;
+        if (_treeViewFiles is null || _miLeaveLastRowCheckBox is null)
+        {
+            return;
+        }
+
+        _treeViewFiles.Style.LeaveLastRow = _miLeaveLastRowCheckBox.CheckedState == CheckState.Checked;
     }
     }
 
 
     private void SetMultiSelect ()
     private void SetMultiSelect ()
     {
     {
-        _miMultiSelect.Checked = !_miMultiSelect.Checked;
-        _treeViewFiles.MultiSelect = (bool)_miMultiSelect.Checked;
+        if (_treeViewFiles is null || _miMultiSelectCheckBox is null)
+        {
+            return;
+        }
+
+        _treeViewFiles.MultiSelect = _miMultiSelectCheckBox.CheckedState == CheckState.Checked;
     }
     }
 
 
     private void SetNerdIcons ()
     private void SetNerdIcons ()
@@ -349,8 +440,13 @@ public class TreeViewFileSystem : Scenario
 
 
     private void SetupFileTree ()
     private void SetupFileTree ()
     {
     {
+        if (_treeViewFiles is null)
+        {
+            return;
+        }
+
         // setup how to build tree
         // setup how to build tree
-        var fs = new FileSystem ();
+        FileSystem fs = new ();
 
 
         IEnumerable<IDirectoryInfo> rootDirs =
         IEnumerable<IDirectoryInfo> rootDirs =
             DriveInfo.GetDrives ().Select (d => fs.DirectoryInfo.New (d.RootDirectory.FullName));
             DriveInfo.GetDrives ().Select (d => fs.DirectoryInfo.New (d.RootDirectory.FullName));
@@ -363,52 +459,14 @@ public class TreeViewFileSystem : Scenario
         _iconProvider.IsOpenGetter = _treeViewFiles.IsExpanded;
         _iconProvider.IsOpenGetter = _treeViewFiles.IsExpanded;
     }
     }
 
 
-    //private void SetupScrollBar ()
-    //{
-    //    // When using scroll bar leave the last row of the control free (for over-rendering with scroll bar)
-    //    _treeViewFiles.Style.LeaveLastRow = true;
-
-    //    var scrollBar = new ScrollBarView (_treeViewFiles, true);
-
-    //    scrollBar.ChangedPosition += (s, e) =>
-    //                                 {
-    //                                     _treeViewFiles.ScrollOffsetVertical = scrollBar.Position;
-
-    //                                     if (_treeViewFiles.ScrollOffsetVertical != scrollBar.Position)
-    //                                     {
-    //                                         scrollBar.Position = _treeViewFiles.ScrollOffsetVertical;
-    //                                     }
-
-    //                                     _treeViewFiles.SetNeedsDraw ();
-    //                                 };
-
-    //    scrollBar.OtherScrollBarView.ChangedPosition += (s, e) =>
-    //                                                    {
-    //                                                        _treeViewFiles.ScrollOffsetHorizontal = scrollBar.OtherScrollBarView.Position;
-
-    //                                                        if (_treeViewFiles.ScrollOffsetHorizontal != scrollBar.OtherScrollBarView.Position)
-    //                                                        {
-    //                                                            scrollBar.OtherScrollBarView.Position = _treeViewFiles.ScrollOffsetHorizontal;
-    //                                                        }
-
-    //                                                        _treeViewFiles.SetNeedsDraw ();
-    //                                                    };
-
-    //    _treeViewFiles.DrawingContent += (s, e) =>
-    //                                  {
-    //                                      scrollBar.Size = _treeViewFiles.ContentHeight;
-    //                                      scrollBar.Position = _treeViewFiles.ScrollOffsetVertical;
-    //                                      scrollBar.OtherScrollBarView.Size = _treeViewFiles.GetContentWidth (true);
-    //                                      scrollBar.OtherScrollBarView.Position = _treeViewFiles.ScrollOffsetHorizontal;
-    //                                      scrollBar.Refresh ();
-    //                                  };
-    //}
-
     private void ShowColoredExpandableSymbols ()
     private void ShowColoredExpandableSymbols ()
     {
     {
-        _miColoredSymbols.Checked = !_miColoredSymbols.Checked;
+        if (_treeViewFiles is null || _miColoredSymbolsCheckBox is null)
+        {
+            return;
+        }
 
 
-        _treeViewFiles.Style.ColorExpandSymbol = (bool)_miColoredSymbols.Checked;
+        _treeViewFiles.Style.ColorExpandSymbol = _miColoredSymbolsCheckBox.CheckedState == CheckState.Checked;
         _treeViewFiles.SetNeedsDraw ();
         _treeViewFiles.SetNeedsDraw ();
     }
     }
 
 
@@ -418,22 +476,31 @@ public class TreeViewFileSystem : Scenario
 
 
         // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
         // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
         // and the context menu is disposed when it is closed.
         // and the context menu is disposed when it is closed.
-        _detailsFrame.App?.Popover?.Register (contextMenu);
+        _detailsFrame?.App?.Popover?.Register (contextMenu);
 
 
         Application.Invoke (() => contextMenu?.MakeVisible (screenPoint));
         Application.Invoke (() => contextMenu?.MakeVisible (screenPoint));
     }
     }
 
 
     private void ShowLines ()
     private void ShowLines ()
     {
     {
-        _miShowLines.Checked = !_miShowLines.Checked;
+        if (_treeViewFiles is null || _miShowLinesCheckBox is null)
+        {
+            return;
+        }
 
 
-        _treeViewFiles.Style.ShowBranchLines = (bool)_miShowLines.Checked!;
+        _treeViewFiles.Style.ShowBranchLines = _miShowLinesCheckBox.CheckedState == CheckState.Checked;
         _treeViewFiles.SetNeedsDraw ();
         _treeViewFiles.SetNeedsDraw ();
     }
     }
 
 
-    private void ShowPropertiesOf (IFileSystemInfo fileSystemInfo) { _detailsFrame.FileInfo = fileSystemInfo; }
+    private void ShowPropertiesOf (IFileSystemInfo fileSystemInfo)
+    {
+        if (_detailsFrame is { })
+        {
+            _detailsFrame.FileInfo = fileSystemInfo;
+        }
+    }
 
 
-    private void TreeViewFiles_DrawLine (object sender, DrawTreeViewLineEventArgs<IFileSystemInfo> e)
+    private void TreeViewFiles_DrawLine (object? sender, DrawTreeViewLineEventArgs<IFileSystemInfo> e)
     {
     {
         // Render directory icons in yellow
         // Render directory icons in yellow
         if (e.Model is IDirectoryInfo d)
         if (e.Model is IDirectoryInfo d)
@@ -454,14 +521,19 @@ public class TreeViewFileSystem : Scenario
         }
         }
     }
     }
 
 
-    private void TreeViewFiles_KeyPress (object sender, Key obj)
+    private void TreeViewFiles_KeyPress (object? sender, Key obj)
     {
     {
+        if (_treeViewFiles is null)
+        {
+            return;
+        }
+
         if (obj.KeyCode == (KeyCode.R | KeyCode.CtrlMask))
         if (obj.KeyCode == (KeyCode.R | KeyCode.CtrlMask))
         {
         {
-            IFileSystemInfo selected = _treeViewFiles.SelectedObject;
+            IFileSystemInfo? selected = _treeViewFiles.SelectedObject;
 
 
             // nothing is selected
             // nothing is selected
-            if (selected == null)
+            if (selected is null)
             {
             {
                 return;
                 return;
             }
             }
@@ -469,7 +541,7 @@ public class TreeViewFileSystem : Scenario
             int? location = _treeViewFiles.GetObjectRow (selected);
             int? location = _treeViewFiles.GetObjectRow (selected);
 
 
             //selected object is offscreen or somehow not found
             //selected object is offscreen or somehow not found
-            if (location == null || location < 0 || location > _treeViewFiles.Frame.Height)
+            if (location is null || location < 0 || location > _treeViewFiles.Frame.Height)
             {
             {
                 return;
                 return;
             }
             }
@@ -484,15 +556,20 @@ public class TreeViewFileSystem : Scenario
         }
         }
     }
     }
 
 
-    private void TreeViewFiles_MouseClick (object sender, MouseEventArgs obj)
+    private void TreeViewFiles_MouseClick (object? sender, MouseEventArgs obj)
     {
     {
+        if (_treeViewFiles is null)
+        {
+            return;
+        }
+
         // if user right clicks
         // if user right clicks
         if (obj.Flags.HasFlag (MouseFlags.Button3Clicked))
         if (obj.Flags.HasFlag (MouseFlags.Button3Clicked))
         {
         {
-            IFileSystemInfo rightClicked = _treeViewFiles.GetObjectOnRow (obj.Position.Y);
+            IFileSystemInfo? rightClicked = _treeViewFiles.GetObjectOnRow (obj.Position.Y);
 
 
             // nothing was clicked
             // nothing was clicked
-            if (rightClicked == null)
+            if (rightClicked is null)
             {
             {
                 return;
                 return;
             }
             }
@@ -507,20 +584,34 @@ public class TreeViewFileSystem : Scenario
         }
         }
     }
     }
 
 
-    private void TreeViewFiles_SelectionChanged (object sender, SelectionChangedEventArgs<IFileSystemInfo> e) { ShowPropertiesOf (e.NewValue); }
+    private void TreeViewFiles_SelectionChanged (object? sender, SelectionChangedEventArgs<IFileSystemInfo> e) { ShowPropertiesOf (e.NewValue); }
 
 
     private void UpdateIconCheckedness ()
     private void UpdateIconCheckedness ()
     {
     {
-        _miBasicIcons.Checked = !_iconProvider.UseNerdIcons && !_iconProvider.UseUnicodeCharacters;
-        _miUnicodeIcons.Checked = _iconProvider.UseUnicodeCharacters;
-        _miNerdIcons.Checked = _iconProvider.UseNerdIcons;
-        _treeViewFiles.SetNeedsDraw ();
+        if (_miBasicIconsCheckBox is { })
+        {
+            _miBasicIconsCheckBox.CheckedState = !_iconProvider.UseNerdIcons && !_iconProvider.UseUnicodeCharacters
+                                                     ? CheckState.Checked
+                                                     : CheckState.UnChecked;
+        }
+
+        if (_miUnicodeIconsCheckBox is { })
+        {
+            _miUnicodeIconsCheckBox.CheckedState = _iconProvider.UseUnicodeCharacters ? CheckState.Checked : CheckState.UnChecked;
+        }
+
+        if (_miNerdIconsCheckBox is { })
+        {
+            _miNerdIconsCheckBox.CheckedState = _iconProvider.UseNerdIcons ? CheckState.Checked : CheckState.UnChecked;
+        }
+
+        _treeViewFiles?.SetNeedsDraw ();
     }
     }
 
 
     private class DetailsFrame : FrameView
     private class DetailsFrame : FrameView
     {
     {
         private readonly FileSystemIconProvider _iconProvider;
         private readonly FileSystemIconProvider _iconProvider;
-        private IFileSystemInfo _fileInfo;
+        private IFileSystemInfo? _fileInfo;
 
 
         public DetailsFrame (FileSystemIconProvider iconProvider)
         public DetailsFrame (FileSystemIconProvider iconProvider)
         {
         {
@@ -530,13 +621,13 @@ public class TreeViewFileSystem : Scenario
             _iconProvider = iconProvider;
             _iconProvider = iconProvider;
         }
         }
 
 
-        public IFileSystemInfo FileInfo
+        public IFileSystemInfo? FileInfo
         {
         {
             get => _fileInfo;
             get => _fileInfo;
             set
             set
             {
             {
                 _fileInfo = value;
                 _fileInfo = value;
-                StringBuilder sb = null;
+                StringBuilder? sb = null;
 
 
                 if (_fileInfo is IFileInfo f)
                 if (_fileInfo is IFileInfo f)
                 {
                 {
@@ -552,12 +643,12 @@ public class TreeViewFileSystem : Scenario
                 {
                 {
                     Title = $"{_iconProvider.GetIconWithOptionalSpace (dir)}{dir.Name}".Trim ();
                     Title = $"{_iconProvider.GetIconWithOptionalSpace (dir)}{dir.Name}".Trim ();
                     sb = new ();
                     sb = new ();
-                    sb.AppendLine ($"Path:\n {dir?.FullName}\n");
+                    sb.AppendLine ($"Path:\n {dir.FullName}\n");
                     sb.AppendLine ($"Modified:\n {dir.LastWriteTime}\n");
                     sb.AppendLine ($"Modified:\n {dir.LastWriteTime}\n");
                     sb.AppendLine ($"Created:\n {dir.CreationTime}\n");
                     sb.AppendLine ($"Created:\n {dir.CreationTime}\n");
                 }
                 }
 
 
-                Text = sb.ToString ();
+                Text = sb?.ToString () ?? string.Empty;
             }
             }
         }
         }
     }
     }

+ 0 - 157
Examples/UICatalog/Scenarios/TrueColors.cs

@@ -1,157 +0,0 @@
-using System;
-
-namespace UICatalog.Scenarios;
-
-[ScenarioMetadata ("True Colors", "Demonstration of true color support.")]
-[ScenarioCategory ("Colors")]
-public class TrueColors : Scenario
-{
-    public override void Main ()
-    {
-        Application.Init ();
-
-        Window app = new ()
-        {
-            Title = GetQuitKeyAndName ()
-        };
-
-        var x = 2;
-        var y = 1;
-
-        bool canTrueColor = Application.Driver?.SupportsTrueColor ?? false;
-
-        var lblDriverName = new Label
-        {
-            X = x, Y = y++, Text = $"Current driver is {Application.Driver?.GetType ().Name}"
-        };
-        app.Add (lblDriverName);
-        y++;
-
-        var cbSupportsTrueColor = new CheckBox
-        {
-            X = x,
-            Y = y++,
-            CheckedState = canTrueColor ? CheckState.Checked : CheckState.UnChecked,
-            CanFocus = false,
-            Enabled = false,
-            Text = "Driver supports true color "
-        };
-        app.Add (cbSupportsTrueColor);
-
-        var cbUseTrueColor = new CheckBox
-        {
-            X = x,
-            Y = y++,
-            CheckedState = Application.Force16Colors ? CheckState.Checked : CheckState.UnChecked,
-            Enabled = canTrueColor,
-            Text = "Force 16 colors"
-        };
-        cbUseTrueColor.CheckedStateChanging += (_, evt) => { Application.Force16Colors = evt.Result == CheckState.Checked; };
-        app.Add (cbUseTrueColor);
-
-        y += 2;
-        SetupGradient ("Red gradient", x, ref y, i => new (i, 0));
-        SetupGradient ("Green gradient", x, ref y, i => new (0, i));
-        SetupGradient ("Blue gradient", x, ref y, i => new (0, 0, i));
-        SetupGradient ("Yellow gradient", x, ref y, i => new (i, i));
-        SetupGradient ("Magenta gradient", x, ref y, i => new (i, 0, i));
-        SetupGradient ("Cyan gradient", x, ref y, i => new (0, i, i));
-        SetupGradient ("Gray gradient", x, ref y, i => new (i, i, i));
-
-        app.Add (
-                 new Label { X = Pos.AnchorEnd (44), Y = 2, Text = "Mouse over to get the gradient view color:" }
-                );
-
-        app.Add (
-                 new Label { X = Pos.AnchorEnd (44), Y = 4, Text = "Red:" }
-                );
-
-        app.Add (
-                 new Label { X = Pos.AnchorEnd (44), Y = 5, Text = "Green:" }
-                );
-
-        app.Add (
-                 new Label { X = Pos.AnchorEnd (44), Y = 6, Text = "Blue:" }
-                );
-
-        app.Add (
-                 new Label { X = Pos.AnchorEnd (44), Y = 8, Text = "Darker:" }
-                );
-
-        app.Add (
-                 new Label { X = Pos.AnchorEnd (44), Y = 9, Text = "Lighter:" }
-                );
-
-        var lblRed = new Label { X = Pos.AnchorEnd (32), Y = 4, Text = "na" };
-        app.Add (lblRed);
-        var lblGreen = new Label { X = Pos.AnchorEnd (32), Y = 5, Text = "na" };
-        app.Add (lblGreen);
-        var lblBlue = new Label { X = Pos.AnchorEnd (32), Y = 6, Text = "na" };
-        app.Add (lblBlue);
-
-        var lblDarker = new Label { X = Pos.AnchorEnd (32), Y = 8, Text = "     " };
-        app.Add (lblDarker);
-
-        var lblLighter = new Label { X = Pos.AnchorEnd (32), Y = 9, Text = "    " };
-        app.Add (lblLighter);
-
-        Application.MouseEvent += (s, e) =>
-                                  {
-                                      if (e.View == null)
-                                      {
-                                          return;
-                                      }
-
-                                      if (e.Flags == MouseFlags.Button1Clicked)
-                                      {
-                                          Attribute normal = e.View.GetAttributeForRole (VisualRole.Normal);
-
-                                          lblLighter.SetScheme (new (e.View.GetScheme ())
-                                          {
-                                              Normal = new (
-                                                            normal.Foreground,
-                                                            normal.Background.GetBrighterColor ()
-                                                           )
-                                          });
-                                      }
-                                      else
-                                      {
-                                          Attribute normal = e.View.GetAttributeForRole (VisualRole.Normal);
-                                          lblRed.Text = normal.Foreground.R.ToString ();
-                                          lblGreen.Text = normal.Foreground.G.ToString ();
-                                          lblBlue.Text = normal.Foreground.B.ToString ();
-                                      }
-                                  };
-        Application.Run (app);
-        app.Dispose ();
-
-        Application.Shutdown ();
-
-        return;
-
-        void SetupGradient (string name, int x, ref int y, Func<int, Color> colorFunc)
-        {
-            var gradient = new Label { X = x, Y = y++, Text = name };
-            app.Add (gradient);
-
-            for (int dx = x, i = 0; i <= 256; i += 4)
-            {
-                var l = new Label
-                {
-                    X = dx++,
-                    Y = y
-                };
-                l.SetScheme (new ()
-                {
-                    Normal = new (
-                                  colorFunc (Math.Clamp (i, 0, 255)),
-                                  colorFunc (Math.Clamp (i, 0, 255))
-                                 )
-                });
-                app.Add (l);
-            }
-
-            y += 2;
-        }
-    }
-}

+ 96 - 94
Examples/UICatalog/Scenarios/Unicode.cs

@@ -1,5 +1,5 @@
-using System.Collections.ObjectModel;
-using System.IO;
+#nullable enable
+
 using System.Text;
 using System.Text;
 
 
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
@@ -15,82 +15,75 @@ public class UnicodeInMenu : Scenario
             "Τὴ γλῶσσα μοῦ ἔδωσαν ἑλληνικὴ\nτὸ σπίτι φτωχικὸ στὶς ἀμμουδιὲς τοῦ Ὁμήρου.\nΜονάχη ἔγνοια ἡ γλῶσσα μου στὶς ἀμμουδιὲς τοῦ Ὁμήρου.";
             "Τὴ γλῶσσα μοῦ ἔδωσαν ἑλληνικὴ\nτὸ σπίτι φτωχικὸ στὶς ἀμμουδιὲς τοῦ Ὁμήρου.\nΜονάχη ἔγνοια ἡ γλῶσσα μου στὶς ἀμμουδιὲς τοῦ Ὁμήρου.";
 
 
         var gitString =
         var gitString =
-            $"gui.cs 糊 (hú) {
-                Glyphs.IdenticalTo
-            } {
-                Glyphs.DownArrow
-            }18 {
-                Glyphs.UpArrow
-            }10 {
-                Glyphs.VerticalFourDots
-            }1 {
-                Glyphs.HorizontalEllipsis
-            }";
-
-        // Init
+            $"gui.cs 糊 (hú) {Glyphs.IdenticalTo} {Glyphs.DownArrow}18 {Glyphs.UpArrow}10 {Glyphs.VerticalFourDots}1 {Glyphs.HorizontalEllipsis}";
+
         Application.Init ();
         Application.Init ();
 
 
-        // Setup - Create a top-level application window and configure it.
         Window appWindow = new ()
         Window appWindow = new ()
         {
         {
-            Title = GetQuitKeyAndName ()
+            Title = GetQuitKeyAndName (),
+            BorderStyle = LineStyle.None
         };
         };
 
 
-        var menu = new MenuBar
-        {
-            Menus =
-            [
-                new (
-                     "_Файл",
-                     new MenuItem []
-                     {
-                         new (
-                              "_Создать",
-                              "Creates new file",
-                              null
-                             ),
-                         new ("_Открыть", "", null),
-                         new ("Со_хранить", "", null),
-                         new (
-                              "_Выход",
-                              "",
-                              () => Application.RequestStop ()
-                             )
-                     }
-                    ),
-                new (
-                     "_Edit",
-                     new MenuItem []
-                     {
-                         new ("_Copy", "", null), new ("C_ut", "", null),
-                         new ("_糊", "hú (Paste)", null)
-                     }
-                    )
-            ]
-        };
-        appWindow.Add (menu);
+        // MenuBar
+        MenuBar menu = new ();
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_Файл",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_Создать",
+                                           HelpText = "Creates new file"
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Открыть"
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "Со_хранить"
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Выход",
+                                           Action = () => Application.RequestStop ()
+                                       }
+                                   ]
+                                  )
+                 );
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_Edit",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_Copy"
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "C_ut"
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_糊",
+                                           HelpText = "hú (Paste)"
+                                       }
+                                   ]
+                                  )
+                 );
 
 
-        var statusBar = new StatusBar (
-                                       [
-                                           new (
-                                                Application.QuitKey,
-                                                "Выход",
-                                                () => Application.RequestStop ()
-                                               ),
-                                           new (Key.F2, "Создать", null),
-                                           new (Key.F3, "Со_хранить", null)
-                                       ]
-                                      );
-        appWindow.Add (statusBar);
+        appWindow.Add (menu);
 
 
-        var label = new Label { X = 0, Y = 1, Text = "Label:" };
+        Label label = new () { X = 0, Y = Pos.Bottom (menu), Text = "Label:" };
         appWindow.Add (label);
         appWindow.Add (label);
 
 
-        var testlabel = new Label
+        Label testlabel = new ()
         {
         {
             X = 20,
             X = 20,
             Y = Pos.Y (label),
             Y = Pos.Y (label),
-
             Width = Dim.Percent (50),
             Width = Dim.Percent (50),
             Text = gitString
             Text = gitString
         };
         };
@@ -98,7 +91,8 @@ public class UnicodeInMenu : Scenario
 
 
         label = new () { X = Pos.X (label), Y = Pos.Bottom (label) + 1, Text = "Label (CanFocus):" };
         label = new () { X = Pos.X (label), Y = Pos.Bottom (label) + 1, Text = "Label (CanFocus):" };
         appWindow.Add (label);
         appWindow.Add (label);
-        var sb = new StringBuilder ();
+
+        StringBuilder sb = new ();
         sb.Append ('e');
         sb.Append ('e');
         sb.Append ('\u0301');
         sb.Append ('\u0301');
         sb.Append ('\u0301');
         sb.Append ('\u0301');
@@ -107,64 +101,59 @@ public class UnicodeInMenu : Scenario
         {
         {
             X = 20,
             X = 20,
             Y = Pos.Y (label),
             Y = Pos.Y (label),
-
             Width = Dim.Percent (50),
             Width = Dim.Percent (50),
             CanFocus = true,
             CanFocus = true,
             HotKeySpecifier = new ('&'),
             HotKeySpecifier = new ('&'),
             Text = $"Should be [e with two accents, but isn't due to #2616]: [{sb}]"
             Text = $"Should be [e with two accents, but isn't due to #2616]: [{sb}]"
         };
         };
         appWindow.Add (testlabel);
         appWindow.Add (testlabel);
+
         label = new () { X = Pos.X (label), Y = Pos.Bottom (label) + 1, Text = "Button:" };
         label = new () { X = Pos.X (label), Y = Pos.Bottom (label) + 1, Text = "Button:" };
         appWindow.Add (label);
         appWindow.Add (label);
-        var button = new Button { X = 20, Y = Pos.Y (label), Text = "A123456789♥♦♣♠JQK" };
+
+        Button button = new () { X = 20, Y = Pos.Y (label), Text = "A123456789♥♦♣♠JQK" };
         appWindow.Add (button);
         appWindow.Add (button);
 
 
         label = new () { X = Pos.X (label), Y = Pos.Bottom (label) + 1, Text = "CheckBox:" };
         label = new () { X = Pos.X (label), Y = Pos.Bottom (label) + 1, Text = "CheckBox:" };
         appWindow.Add (label);
         appWindow.Add (label);
 
 
-        var checkBox = new CheckBox
+        CheckBox checkBox = new ()
         {
         {
             X = 20,
             X = 20,
             Y = Pos.Y (label),
             Y = Pos.Y (label),
-
             Width = Dim.Percent (50),
             Width = Dim.Percent (50),
             Height = 1,
             Height = 1,
             Text = gitString
             Text = gitString
         };
         };
+        appWindow.Add (checkBox);
 
 
-        var checkBoxRight = new CheckBox
+        CheckBox checkBoxRight = new ()
         {
         {
             X = 20,
             X = 20,
             Y = Pos.Bottom (checkBox),
             Y = Pos.Bottom (checkBox),
-
             Width = Dim.Percent (50),
             Width = Dim.Percent (50),
             Height = 1,
             Height = 1,
             TextAlignment = Alignment.End,
             TextAlignment = Alignment.End,
             Text = $"End - {gitString}"
             Text = $"End - {gitString}"
         };
         };
-        appWindow.Add (checkBox, checkBoxRight);
-
-        //label = new () { X = Pos.X (label), Y = Pos.Bottom (checkBoxRight) + 1, Text = "ComboBox:" };
-        //appWindow.Add (label);
-        //var comboBox = new ComboBox { X = 20, Y = Pos.Y (label), Width = Dim.Percent (50) };
-        //comboBox.SetSource (new ObservableCollection<string> { gitString, "Со_хранить" });
+        appWindow.Add (checkBoxRight);
 
 
-        //appWindow.Add (comboBox);
-        //comboBox.Text = gitString;
-
-        label = new () { X = Pos.X (label), Y = Pos.Bottom (label) + 2, Text = "HexView:" };
+        label = new () { X = Pos.X (label), Y = Pos.Bottom (checkBoxRight) + 2, Text = "HexView:" };
         appWindow.Add (label);
         appWindow.Add (label);
 
 
-        var hexView = new HexView (new MemoryStream (Encoding.ASCII.GetBytes (gitString + " Со_хранить")))
+        HexView hexView = new (new MemoryStream (Encoding.ASCII.GetBytes (gitString + " Со_хранить")))
         {
         {
-            X = 20, Y = Pos.Y (label), Width = Dim.Percent (60), Height = 5
+            X = 20,
+            Y = Pos.Y (label),
+            Width = Dim.Percent (60),
+            Height = 5
         };
         };
         appWindow.Add (hexView);
         appWindow.Add (hexView);
 
 
         label = new () { X = Pos.X (label), Y = Pos.Bottom (hexView) + 1, Text = "ListView:" };
         label = new () { X = Pos.X (label), Y = Pos.Bottom (hexView) + 1, Text = "ListView:" };
         appWindow.Add (label);
         appWindow.Add (label);
 
 
-        var listView = new ListView
+        ListView listView = new ()
         {
         {
             X = 20,
             X = 20,
             Y = Pos.Y (label),
             Y = Pos.Y (label),
@@ -179,28 +168,31 @@ public class UnicodeInMenu : Scenario
         label = new () { X = Pos.X (label), Y = Pos.Bottom (listView) + 1, Text = "OptionSelector:" };
         label = new () { X = Pos.X (label), Y = Pos.Bottom (listView) + 1, Text = "OptionSelector:" };
         appWindow.Add (label);
         appWindow.Add (label);
 
 
-        var optionSelector = new OptionSelector
+        OptionSelector optionSelector = new ()
         {
         {
             X = 20,
             X = 20,
             Y = Pos.Y (label),
             Y = Pos.Y (label),
             Width = Dim.Percent (60),
             Width = Dim.Percent (60),
-            Labels = new [] { "item #1", gitString, "Со_хранить", "𝔽𝕆𝕆𝔹𝔸ℝ" }
+            Labels = ["item #1", gitString, "Со_хранить", "𝔽𝕆𝕆𝔹𝔸ℝ"]
         };
         };
         appWindow.Add (optionSelector);
         appWindow.Add (optionSelector);
 
 
         label = new () { X = Pos.X (label), Y = Pos.Bottom (optionSelector) + 1, Text = "TextField:" };
         label = new () { X = Pos.X (label), Y = Pos.Bottom (optionSelector) + 1, Text = "TextField:" };
         appWindow.Add (label);
         appWindow.Add (label);
 
 
-        var textField = new TextField
+        TextField textField = new ()
         {
         {
-            X = 20, Y = Pos.Y (label), Width = Dim.Percent (60), Text = gitString + " = Со_хранить"
+            X = 20,
+            Y = Pos.Y (label),
+            Width = Dim.Percent (60),
+            Text = gitString + " = Со_хранить"
         };
         };
         appWindow.Add (textField);
         appWindow.Add (textField);
 
 
         label = new () { X = Pos.X (label), Y = Pos.Bottom (textField) + 1, Text = "TextView:" };
         label = new () { X = Pos.X (label), Y = Pos.Bottom (textField) + 1, Text = "TextView:" };
         appWindow.Add (label);
         appWindow.Add (label);
 
 
-        var textView = new TextView
+        TextView textView = new ()
         {
         {
             X = 20,
             X = 20,
             Y = Pos.Y (label),
             Y = Pos.Y (label),
@@ -210,12 +202,22 @@ public class UnicodeInMenu : Scenario
         };
         };
         appWindow.Add (textView);
         appWindow.Add (textView);
 
 
-        // Run - Start the application.
-        Application.Run (appWindow);
+        // StatusBar
+        StatusBar statusBar = new (
+                                   [
+                                       new (
+                                            Application.QuitKey,
+                                            "Выход",
+                                            () => Application.RequestStop ()
+                                           ),
+                                       new (Key.F2, "Создать", null),
+                                       new (Key.F3, "Со_хранить", null)
+                                   ]
+                                  );
+        appWindow.Add (statusBar);
 
 
+        Application.Run (appWindow);
         appWindow.Dispose ();
         appWindow.Dispose ();
-
-        // Shutdown - Calling Application.Shutdown is required.
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 }
 }

+ 3 - 3
Examples/UICatalog/Scenarios/ViewportSettings.cs

@@ -102,7 +102,7 @@ public class ViewportSettings : Scenario
             Title = GetQuitKeyAndName (),
             Title = GetQuitKeyAndName (),
 
 
             // Use a different colorscheme so ViewSettings.ClearContentOnly is obvious
             // Use a different colorscheme so ViewSettings.ClearContentOnly is obvious
-            SchemeName = "Toplevel",
+            SchemeName = "Runnable",
             BorderStyle = LineStyle.None
             BorderStyle = LineStyle.None
         };
         };
 
 
@@ -169,13 +169,13 @@ public class ViewportSettings : Scenario
         };
         };
 
 
         charMap.Accepting += (s, e) =>
         charMap.Accepting += (s, e) =>
-                              MessageBox.Query (20, 7, "Hi", $"Am I a {view.GetType ().Name}?", "Yes", "No");
+                              MessageBox.Query ((s as View)?.App, 20, 7, "Hi", $"Am I a {view.GetType ().Name}?", "Yes", "No");
 
 
         var buttonAnchored = new Button
         var buttonAnchored = new Button
         {
         {
             X = Pos.AnchorEnd () - 10, Y = Pos.AnchorEnd () - 4, Text = "Bottom Rig_ht"
             X = Pos.AnchorEnd () - 10, Y = Pos.AnchorEnd () - 4, Text = "Bottom Rig_ht"
         };
         };
-        buttonAnchored.Accepting += (sender, args) => MessageBox.Query ("Hi", $"You pressed {((Button)sender)?.Text}", "_Ok");
+        buttonAnchored.Accepting += (sender, args) => MessageBox.Query ((sender as View)?.App, "Hi", $"You pressed {((Button)sender)?.Text}", "_Ok");
 
 
         view.Margin!.Data = "Margin";
         view.Margin!.Data = "Margin";
         view.Margin!.Thickness = new (0);
         view.Margin!.Thickness = new (0);

+ 4 - 4
Examples/UICatalog/Scenarios/WindowsAndFrameViews.cs

@@ -16,9 +16,9 @@ public class WindowsAndFrameViews : Scenario
             Title = GetQuitKeyAndName ()
             Title = GetQuitKeyAndName ()
         };
         };
 
 
-        static int About ()
+        static int? About ()
         {
         {
-            return MessageBox.Query (
+            return MessageBox.Query (ApplicationImpl.Instance,
                                      "About UI Catalog",
                                      "About UI Catalog",
                                      "UI Catalog is a comprehensive sample library for Terminal.Gui",
                                      "UI Catalog is a comprehensive sample library for Terminal.Gui",
                                      "Ok"
                                      "Ok"
@@ -69,7 +69,7 @@ public class WindowsAndFrameViews : Scenario
         // add it to our list
         // add it to our list
         listWin.Add (win);
         listWin.Add (win);
 
 
-        // create 3 more Windows in a loop, adding them Application.Current
+        // create 3 more Windows in a loop, adding them Application.TopRunnable
         // Each with a
         // Each with a
         //	button
         //	button
         //  sub Window with
         //  sub Window with
@@ -99,7 +99,7 @@ public class WindowsAndFrameViews : Scenario
             };
             };
 
 
             pressMeButton.Accepting += (s, e) =>
             pressMeButton.Accepting += (s, e) =>
-                                        MessageBox.ErrorQuery (loopWin.Title, "Neat?", "Yes", "No");
+                                        MessageBox.ErrorQuery ((s as View)?.App, loopWin.Title, "Neat?", "Yes", "No");
             loopWin.Add (pressMeButton);
             loopWin.Add (pressMeButton);
 
 
             var subWin = new Window
             var subWin = new Window

+ 78 - 75
Examples/UICatalog/Scenarios/WizardAsView.cs

@@ -1,4 +1,5 @@
-
+#nullable enable
+
 namespace UICatalog.Scenarios;
 namespace UICatalog.Scenarios;
 
 
 [ScenarioMetadata ("WizardAsView", "Shows using the Wizard class in an non-modal way")]
 [ScenarioMetadata ("WizardAsView", "Shows using the Wizard class in an non-modal way")]
@@ -9,65 +10,63 @@ public class WizardAsView : Scenario
     {
     {
         Application.Init ();
         Application.Init ();
 
 
-        var menu = new MenuBar
-        {
-            Menus =
-            [
-                new MenuBarItem (
-                                 "_File",
-                                 new MenuItem []
-                                 {
-                                     new (
-                                          "_Restart Configuration...",
-                                          "",
-                                          () => MessageBox.Query (
-                                                                  "Wizaard",
-                                                                  "Are you sure you want to reset the Wizard and start over?",
-                                                                  "Ok",
-                                                                  "Cancel"
-                                                                 )
-                                         ),
-                                     new (
-                                          "Re_boot Server...",
-                                          "",
-                                          () => MessageBox.Query (
-                                                                  "Wizaard",
-                                                                  "Are you sure you want to reboot the server start over?",
-                                                                  "Ok",
-                                                                  "Cancel"
-                                                                 )
-                                         ),
-                                     new (
-                                          "_Shutdown Server...",
-                                          "",
-                                          () => MessageBox.Query (
-                                                                  "Wizaard",
-                                                                  "Are you sure you want to cancel setup and shutdown?",
-                                                                  "Ok",
-                                                                  "Cancel"
-                                                                 )
-                                         )
-                                 }
-                                )
-            ]
-        };
-
-        Toplevel topLevel = new ();
-        topLevel.Add (menu);
+        // MenuBar
+        MenuBar menu = new ();
+
+        menu.Add (
+                  new MenuBarItem (
+                                   "_File",
+                                   [
+                                       new MenuItem
+                                       {
+                                           Title = "_Restart Configuration...",
+                                           Action = () => MessageBox.Query (
+                                                                            ApplicationImpl.Instance,
+                                                                            "Wizard",
+                                                                            "Are you sure you want to reset the Wizard and start over?",
+                                                                            "Ok",
+                                                                            "Cancel"
+                                                                           )
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "Re_boot Server...",
+                                           Action = () => MessageBox.Query (
+                                                                            ApplicationImpl.Instance,
+                                                                            "Wizard",
+                                                                            "Are you sure you want to reboot the server start over?",
+                                                                            "Ok",
+                                                                            "Cancel"
+                                                                           )
+                                       },
+                                       new MenuItem
+                                       {
+                                           Title = "_Shutdown Server...",
+                                           Action = () => MessageBox.Query (
+                                                                            ApplicationImpl.Instance,
+                                                                            "Wizard",
+                                                                            "Are you sure you want to cancel setup and shutdown?",
+                                                                            "Ok",
+                                                                            "Cancel"
+                                                                           )
+                                       }
+                                   ]
+                                  )
+                 );
 
 
         // No need for a Title because the border is disabled
         // No need for a Title because the border is disabled
-        var wizard = new Wizard
+        Wizard wizard = new ()
         {
         {
             X = 0,
             X = 0,
-            Y = 0,
+            Y = Pos.Bottom (menu),
             Width = Dim.Fill (),
             Width = Dim.Fill (),
             Height = Dim.Fill (),
             Height = Dim.Fill (),
             ShadowStyle = ShadowStyle.None
             ShadowStyle = ShadowStyle.None
         };
         };
 
 
-        // Set Mdoal to false to cause the Wizard class to render without a frame and
+        // Set Modal to false to cause the Wizard class to render without a frame and
         // behave like an non-modal View (vs. a modal/pop-up Window).
         // behave like an non-modal View (vs. a modal/pop-up Window).
-        wizard.Modal = false;
+       // wizard.Modal = false;
 
 
         wizard.MovingBack += (s, args) =>
         wizard.MovingBack += (s, args) =>
                              {
                              {
@@ -84,13 +83,13 @@ public class WizardAsView : Scenario
         wizard.Finished += (s, args) =>
         wizard.Finished += (s, args) =>
                            {
                            {
                                //args.Cancel = true;
                                //args.Cancel = true;
-                               MessageBox.Query ("Setup Wizard", "Finished", "Ok");
+                               MessageBox.Query ((s as View)?.App, "Setup Wizard", "Finished", "Ok");
                                Application.RequestStop ();
                                Application.RequestStop ();
                            };
                            };
 
 
         wizard.Cancelled += (s, args) =>
         wizard.Cancelled += (s, args) =>
                             {
                             {
-                                int btn = MessageBox.Query ("Setup Wizard", "Are you sure you want to cancel?", "Yes", "No");
+                                int? btn = MessageBox.Query ((s as View)?.App, "Setup Wizard", "Are you sure you want to cancel?", "Yes", "No");
                                 args.Cancel = btn == 1;
                                 args.Cancel = btn == 1;
 
 
                                 if (btn == 0)
                                 if (btn == 0)
@@ -100,7 +99,7 @@ public class WizardAsView : Scenario
                             };
                             };
 
 
         // Add 1st step
         // Add 1st step
-        var firstStep = new WizardStep { Title = "End User License Agreement" };
+        WizardStep firstStep = new () { Title = "End User License Agreement" };
         wizard.AddStep (firstStep);
         wizard.AddStep (firstStep);
         firstStep.NextButtonText = "Accept!";
         firstStep.NextButtonText = "Accept!";
 
 
@@ -108,48 +107,52 @@ public class WizardAsView : Scenario
             "This is the End User License Agreement.\n\n\n\n\n\nThis is a test of the emergency broadcast system. This is a test of the emergency broadcast system.\nThis is a test of the emergency broadcast system.\n\n\nThis is a test of the emergency broadcast system.\n\nThis is a test of the emergency broadcast system.\n\n\n\nThe end of the EULA.";
             "This is the End User License Agreement.\n\n\n\n\n\nThis is a test of the emergency broadcast system. This is a test of the emergency broadcast system.\nThis is a test of the emergency broadcast system.\n\n\nThis is a test of the emergency broadcast system.\n\nThis is a test of the emergency broadcast system.\n\n\n\nThe end of the EULA.";
 
 
         // Add 2nd step
         // Add 2nd step
-        var secondStep = new WizardStep { Title = "Second Step" };
+        WizardStep secondStep = new () { Title = "Second Step" };
         wizard.AddStep (secondStep);
         wizard.AddStep (secondStep);
 
 
         secondStep.HelpText =
         secondStep.HelpText =
             "This is the help text for the Second Step.\n\nPress the button to change the Title.\n\nIf First Name is empty the step will prevent moving to the next step.";
             "This is the help text for the Second Step.\n\nPress the button to change the Title.\n\nIf First Name is empty the step will prevent moving to the next step.";
 
 
-        var buttonLbl = new Label { Text = "Second Step Button: ", X = 0, Y = 0 };
+        Label buttonLbl = new () { Text = "Second Step Button: ", X = 0, Y = 0 };
 
 
-        var button = new Button
+        Button button = new ()
         {
         {
-            Text = "Press Me to Rename Step", X = Pos.Right (buttonLbl), Y = Pos.Top (buttonLbl)
+            Text = "Press Me to Rename Step",
+            X = Pos.Right (buttonLbl),
+            Y = Pos.Top (buttonLbl)
         };
         };
 
 
         button.Accepting += (s, e) =>
         button.Accepting += (s, e) =>
-                          {
-                              secondStep.Title = "2nd Step";
-
-                              MessageBox.Query (
-                                                "Wizard Scenario",
-                                                "This Wizard Step's title was changed to '2nd Step'",
-                                                "Ok"
-                                               );
-                          };
+                            {
+                                secondStep.Title = "2nd Step";
+
+                                MessageBox.Query ((s as View)?.App,
+                                                  "Wizard Scenario",
+                                                  "This Wizard Step's title was changed to '2nd Step'",
+                                                  "Ok"
+                                                 );
+                            };
         secondStep.Add (buttonLbl, button);
         secondStep.Add (buttonLbl, button);
-        var lbl = new Label { Text = "First Name: ", X = Pos.Left (buttonLbl), Y = Pos.Bottom (buttonLbl) };
-        var firstNameField = new TextField { Text = "Number", Width = 30, X = Pos.Right (lbl), Y = Pos.Top (lbl) };
+
+        Label lbl = new () { Text = "First Name: ", X = Pos.Left (buttonLbl), Y = Pos.Bottom (buttonLbl) };
+        TextField firstNameField = new () { Text = "Number", Width = 30, X = Pos.Right (lbl), Y = Pos.Top (lbl) };
         secondStep.Add (lbl, firstNameField);
         secondStep.Add (lbl, firstNameField);
-        lbl = new Label { Text = "Last Name:  ", X = Pos.Left (buttonLbl), Y = Pos.Bottom (lbl) };
-        var lastNameField = new TextField { Text = "Six", Width = 30, X = Pos.Right (lbl), Y = Pos.Top (lbl) };
+        lbl = new () { Text = "Last Name:  ", X = Pos.Left (buttonLbl), Y = Pos.Bottom (lbl) };
+        TextField lastNameField = new () { Text = "Six", Width = 30, X = Pos.Right (lbl), Y = Pos.Top (lbl) };
         secondStep.Add (lbl, lastNameField);
         secondStep.Add (lbl, lastNameField);
 
 
         // Add last step
         // Add last step
-        var lastStep = new WizardStep { Title = "The last step" };
+        WizardStep lastStep = new () { Title = "The last step" };
         wizard.AddStep (lastStep);
         wizard.AddStep (lastStep);
 
 
         lastStep.HelpText =
         lastStep.HelpText =
             "The wizard is complete!\n\nPress the Finish button to continue.\n\nPressing Esc will cancel.";
             "The wizard is complete!\n\nPress the Finish button to continue.\n\nPressing Esc will cancel.";
 
 
-        wizard.Y = Pos.Bottom (menu);
-        topLevel.Add (wizard);
-        Application.Run (topLevel);
-        topLevel.Dispose ();
+        Window window = new ();
+        window.Add (menu, wizard);
+
+        Application.Run (window);
+        window.Dispose ();
         Application.Shutdown ();
         Application.Shutdown ();
     }
     }
 }
 }

Some files were not shown because too many files changed in this diff