diff --git a/.github/workflows/nuget.yml b/.github/workflows/nuget.yml index a9cd51c..2c573a6 100644 --- a/.github/workflows/nuget.yml +++ b/.github/workflows/nuget.yml @@ -28,11 +28,13 @@ jobs: create_nuget: runs-on: windows-latest env: - COMMIT_SHA: ${{ github.sha || github.event.pull_request.head.sha }} + COMMIT_SHA: ${{ github.sha || github.event.pull_request.head.sha }} steps: - uses: actions/checkout@v3 - - name: Setup .NET - uses: actions/setup-dotnet@v3 + - name: Setup dotnet ${{ matrix.dotnet-version }} + uses: actions/setup-dotnet@v4 + with: + dotnet-version: "9.0.x" - run: | If (('${{ github.event_name }}' -eq 'release') -and ('${{ github.ref_name }}' -match '^(?\d+\.\d+\.\d+)')) { Add-Content -Path $Env:GITHUB_ENV -Value "VERSION=$($Matches.version)" @@ -57,8 +59,10 @@ jobs: runs-on: windows-latest needs: [ create_nuget ] steps: - - name: Setup .NET - uses: actions/setup-dotnet@v3 + - name: Setup dotnet ${{ matrix.dotnet-version }} + uses: actions/setup-dotnet@v4 + with: + dotnet-version: "9.0.x" - uses: actions/download-artifact@v3 with: name: nuget diff --git a/Examples/ShowcaseApp.WPF/App.xaml.cs b/Examples/ShowcaseApp.WPF/App.xaml.cs index ba9983d..d529386 100644 --- a/Examples/ShowcaseApp.WPF/App.xaml.cs +++ b/Examples/ShowcaseApp.WPF/App.xaml.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Linq; -using System.Windows; - -namespace ShowcaseApp.WPF +namespace ShowcaseApp.WPF { /// /// Interaction logic for App.xaml /// - public partial class App : Application + public partial class App { } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Assets/ModernUI.Snowflakes.xaml b/Examples/ShowcaseApp.WPF/Assets/ModernUI.Snowflakes.xaml index 398e507..86b62fd 100644 --- a/Examples/ShowcaseApp.WPF/Assets/ModernUI.Snowflakes.xaml +++ b/Examples/ShowcaseApp.WPF/Assets/ModernUI.Snowflakes.xaml @@ -1,6 +1,5 @@  + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> diff --git a/Examples/ShowcaseApp.WPF/Content/SettingsAppearance.xaml b/Examples/ShowcaseApp.WPF/Content/SettingsAppearance.xaml index 019481e..d9e2efc 100644 --- a/Examples/ShowcaseApp.WPF/Content/SettingsAppearance.xaml +++ b/Examples/ShowcaseApp.WPF/Content/SettingsAppearance.xaml @@ -1,10 +1,9 @@  @@ -21,7 +20,7 @@ - + @@ -33,7 +32,7 @@ - + @@ -42,15 +41,21 @@ - + - - + + - - + + - + \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Content/SettingsAppearance.xaml.cs b/Examples/ShowcaseApp.WPF/Content/SettingsAppearance.xaml.cs index 1a374ab..2258b4d 100644 --- a/Examples/ShowcaseApp.WPF/Content/SettingsAppearance.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Content/SettingsAppearance.xaml.cs @@ -1,18 +1,16 @@ -using System.Windows.Controls; - -namespace ShowcaseApp.WPF.Content +namespace ShowcaseApp.WPF.Content { /// /// Interaction logic for SettingsAppearance.xaml /// - public partial class SettingsAppearance : UserControl + public partial class SettingsAppearance { public SettingsAppearance() { InitializeComponent(); // a simple view model for appearance configuration - this.DataContext = new SettingsAppearanceViewModel(); + DataContext = new SettingsAppearanceViewModel(); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Content/SettingsAppearanceViewModel.cs b/Examples/ShowcaseApp.WPF/Content/SettingsAppearanceViewModel.cs index fc13104..29c8bb2 100644 --- a/Examples/ShowcaseApp.WPF/Content/SettingsAppearanceViewModel.cs +++ b/Examples/ShowcaseApp.WPF/Content/SettingsAppearanceViewModel.cs @@ -19,7 +19,8 @@ public class SettingsAppearanceViewModel private const string PaletteWP = "windows phone"; // 9 accent colors from metro design principles - private Color[] metroAccentColors = new Color[]{ + private readonly Color[] metroAccentColors = + [ Color.FromRgb(0x33, 0x99, 0xff), // blue Color.FromRgb(0x00, 0xab, 0xa9), // teal Color.FromRgb(0x33, 0x99, 0x33), // green @@ -28,11 +29,12 @@ public class SettingsAppearanceViewModel Color.FromRgb(0xff, 0x45, 0x00), // orange red Color.FromRgb(0xe5, 0x14, 0x00), // red Color.FromRgb(0xff, 0x00, 0x97), // magenta - Color.FromRgb(0xa2, 0x00, 0xff), // purple - }; + Color.FromRgb(0xa2, 0x00, 0xff) // purple + ]; // 20 accent colors from Windows Phone 8 - private Color[] wpAccentColors = new Color[]{ + private readonly Color[] wpAccentColors = + [ Color.FromRgb(0xa4, 0xc4, 0x00), // lime Color.FromRgb(0x60, 0xa9, 0x17), // green Color.FromRgb(0x00, 0x8a, 0x00), // emerald @@ -52,26 +54,26 @@ public class SettingsAppearanceViewModel Color.FromRgb(0x6d, 0x87, 0x64), // olive Color.FromRgb(0x64, 0x76, 0x87), // steel Color.FromRgb(0x76, 0x60, 0x8a), // mauve - Color.FromRgb(0x87, 0x79, 0x4e), // taupe - }; + Color.FromRgb(0x87, 0x79, 0x4e) // taupe + ]; private string selectedPalette = PaletteWP; private Color selectedAccentColor; - private LinkCollection themes = new LinkCollection(); + private readonly LinkCollection themes = []; private Link selectedTheme; private string selectedFontSize; public SettingsAppearanceViewModel() { // add the default themes - this.themes.Add(new Link { DisplayName = "dark", Source = AppearanceManager.DarkThemeSource }); - this.themes.Add(new Link { DisplayName = "light", Source = AppearanceManager.LightThemeSource }); + themes.Add(new Link { DisplayName = "dark", Source = AppearanceManager.DarkThemeSource }); + themes.Add(new Link { DisplayName = "light", Source = AppearanceManager.LightThemeSource }); // add additional themes - this.themes.Add(new Link { DisplayName = "snowflakes", Source = new Uri("/ShowcaseApp.WPF;component/Assets/ModernUI.Snowflakes.xaml", UriKind.Relative) }); + themes.Add(new Link { DisplayName = "snowflakes", Source = new Uri("/ShowcaseApp.WPF;component/Assets/ModernUI.Snowflakes.xaml", UriKind.Relative) }); - this.SelectedFontSize = AppearanceManager.Current.FontSize == FontSize.Large ? FontLarge : FontSmall; + SelectedFontSize = AppearanceManager.Current.FontSize == FontSize.Large ? FontLarge : FontSmall; SyncThemeAndColor(); AppearanceManager.Current.PropertyChanged += OnAppearanceManagerPropertyChanged; @@ -80,10 +82,10 @@ public SettingsAppearanceViewModel() private void SyncThemeAndColor() { // synchronizes the selected viewmodel theme with the actual theme used by the appearance manager. - this.SelectedTheme = this.themes.FirstOrDefault(l => l.Source.Equals(AppearanceManager.Current.ThemeSource)); + SelectedTheme = themes.FirstOrDefault(l => l.Source.Equals(AppearanceManager.Current.ThemeSource)); // and make sure accent color is up-to-date - this.SelectedAccentColor = AppearanceManager.Current.AccentColor; + SelectedAccentColor = AppearanceManager.Current.AccentColor; } private void OnAppearanceManagerPropertyChanged(object sender, PropertyChangedEventArgs e) @@ -93,47 +95,35 @@ private void OnAppearanceManagerPropertyChanged(object sender, PropertyChangedEv } } - public LinkCollection Themes - { - get { return this.themes; } - } + public LinkCollection Themes => themes; - public string[] FontSizes - { - get { return new string[] { FontSmall, FontLarge }; } - } + public string[] FontSizes => [FontSmall, FontLarge]; - public string[] Palettes - { - get { return new string[] { PaletteMetro, PaletteWP }; } - } + public string[] Palettes => [PaletteMetro, PaletteWP]; - public Color[] AccentColors - { - get { return this.selectedPalette == PaletteMetro ? this.metroAccentColors : this.wpAccentColors; } - } + public Color[] AccentColors => selectedPalette == PaletteMetro ? metroAccentColors : wpAccentColors; public string SelectedPalette { - get { return this.selectedPalette; } + get => selectedPalette; set { - if (this.selectedPalette != value) { - this.selectedPalette = value; + if (selectedPalette != value) { + selectedPalette = value; OnPropertyChanged("AccentColors"); - this.SelectedAccentColor = this.AccentColors.FirstOrDefault(); + SelectedAccentColor = AccentColors.FirstOrDefault(); } } } public Link SelectedTheme { - get { return this.selectedTheme; } + get => selectedTheme; set { - if (this.selectedTheme != value) { - this.selectedTheme = value; + if (selectedTheme != value) { + selectedTheme = value; OnPropertyChanged("SelectedTheme"); // and update the actual theme @@ -144,11 +134,11 @@ public Link SelectedTheme public string SelectedFontSize { - get { return this.selectedFontSize; } + get => selectedFontSize; set { - if (this.selectedFontSize != value) { - this.selectedFontSize = value; + if (selectedFontSize != value) { + selectedFontSize = value; OnPropertyChanged("SelectedFontSize"); AppearanceManager.Current.FontSize = value == FontLarge ? FontSize.Large : FontSize.Small; @@ -158,11 +148,11 @@ public string SelectedFontSize public Color SelectedAccentColor { - get { return this.selectedAccentColor; } + get => selectedAccentColor; set { - if (this.selectedAccentColor != value) { - this.selectedAccentColor = value; + if (selectedAccentColor != value) { + selectedAccentColor = value; OnPropertyChanged("SelectedAccentColor"); AppearanceManager.Current.AccentColor = value; diff --git a/Examples/ShowcaseApp.WPF/Controls/MiniContentPage.xaml b/Examples/ShowcaseApp.WPF/Controls/MiniContentPage.xaml index 4d47c21..477e7dd 100644 --- a/Examples/ShowcaseApp.WPF/Controls/MiniContentPage.xaml +++ b/Examples/ShowcaseApp.WPF/Controls/MiniContentPage.xaml @@ -1,4 +1,4 @@ - /// Interaction logic for MiniContentPage.xaml /// - public partial class MiniContentPage : UserControl, ISpecialWindowContentIntro, INotifyPropertyChanged + public partial class MiniContentPage : ISpecialWindowContentIntro, INotifyPropertyChanged { public MiniContentPage() { @@ -16,13 +14,23 @@ public MiniContentPage() } private string _text; - public string IntroText { get { return _text; } set { _text = value; OnPropertyChanged("IntroText"); } } + + public string IntroText + { + get => _text; + set + { + _text = value; + OnPropertyChanged(nameof(IntroText)); + } + } + public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; - if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Controls/MiniXamlPage.xaml b/Examples/ShowcaseApp.WPF/Controls/MiniXamlPage.xaml index 98a66e1..c13c103 100644 --- a/Examples/ShowcaseApp.WPF/Controls/MiniXamlPage.xaml +++ b/Examples/ShowcaseApp.WPF/Controls/MiniXamlPage.xaml @@ -1,4 +1,4 @@ - /// Interaction logic for MiniContentPage.xaml /// - public partial class MiniXamlPage : UserControl, ISpecialWindowContentXaml, INotifyPropertyChanged + public partial class MiniXamlPage : ISpecialWindowContentXaml, INotifyPropertyChanged { public MiniXamlPage() { @@ -25,7 +23,7 @@ public MiniXamlPage() public string XamlText { - get { return _text; } + get => _text; set { _text = value; @@ -33,12 +31,13 @@ public string XamlText OnPropertyChanged("XamlText"); } } + public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; - if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Controls/MiniXamlTemplatePage.xaml b/Examples/ShowcaseApp.WPF/Controls/MiniXamlTemplatePage.xaml index 9279c4b..5c48365 100644 --- a/Examples/ShowcaseApp.WPF/Controls/MiniXamlTemplatePage.xaml +++ b/Examples/ShowcaseApp.WPF/Controls/MiniXamlTemplatePage.xaml @@ -1,4 +1,4 @@ - /// Interaction logic for MiniContentPage.xaml /// - public partial class MiniXamlTemplatePage : UserControl, ISpecialWindowContentXamlTemplate, INotifyPropertyChanged + public partial class MiniXamlTemplatePage : ISpecialWindowContentXamlTemplate, INotifyPropertyChanged { public MiniXamlTemplatePage() { @@ -22,9 +20,10 @@ public MiniXamlTemplatePage() } private string _text; + public string XamlText { - get { return _text; } + get => _text; set { _text = value; @@ -32,12 +31,13 @@ public string XamlText OnPropertyChanged("XamlText"); } } + public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; - if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Controls/SpecialWindowControl.xaml.cs b/Examples/ShowcaseApp.WPF/Controls/SpecialWindowControl.xaml.cs index 100b957..1e5579e 100644 --- a/Examples/ShowcaseApp.WPF/Controls/SpecialWindowControl.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Controls/SpecialWindowControl.xaml.cs @@ -2,7 +2,6 @@ using System.Threading; using System.Threading.Tasks; using System.Windows; -using System.Windows.Controls; using FirstFloor.ModernUI; using FirstFloor.ModernUI.Windows; using ShowcaseApp.WPF.Models; @@ -12,23 +11,18 @@ namespace ShowcaseApp.WPF.Controls /// /// Interaction logic for SpecialWindowControl.xaml /// - public partial class SpecialWindowControl : UserControl + public partial class SpecialWindowControl { public SpecialWindowControl(object type) { InitializeComponent(); - tabControl.ContentLoader = new SpecialContentLoader((MiniSpecialType?) type ?? MiniSpecialType.None); + tabControl.ContentLoader = new SpecialContentLoader((MiniSpecialType?)type ?? MiniSpecialType.None); } } - internal class SpecialContentLoader: IContentLoader + internal class SpecialContentLoader(MiniSpecialType type) : IContentLoader { - public MiniSpecialType OpType { get; private set; } - - public SpecialContentLoader(MiniSpecialType type) - { - OpType = type; - } + public MiniSpecialType OpType { get; private set; } = type; public Task LoadContentAsync(Uri uri, CancellationToken cancellationToken) { @@ -37,7 +31,8 @@ public Task LoadContentAsync(Uri uri, CancellationToken cancellationToke // scheduler ensures LoadContent is executed on the current UI thread var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); - return Task.Factory.StartNew(() => LoadContent(uri), cancellationToken, TaskCreationOptions.None, scheduler); + return Task.Factory.StartNew(() => LoadContent(uri), cancellationToken, TaskCreationOptions.None, + scheduler); } protected virtual object LoadContent(Uri uri) @@ -46,17 +41,14 @@ protected virtual object LoadContent(Uri uri) if (ModernUIHelper.IsInDesignMode) return null; var result = Application.LoadComponent(uri); - var spContent = result as ISpecialWindowContentIntro; - if(spContent != null) + if (result is ISpecialWindowContentIntro spContent) spContent.IntroText = Properties.Resources.ResourceManager.GetString(OpType + "Text"); - var spContent2 = result as ISpecialWindowContentXaml; - if (spContent2 != null) + if (result is ISpecialWindowContentXaml spContent2) spContent2.XamlText = Properties.Resources.ResourceManager.GetString(OpType.ToString()); - var spContent3 = result as ISpecialWindowContentXamlTemplate; - if (spContent3 != null) + if (result is ISpecialWindowContentXamlTemplate spContent3) { var xamlTemplate = Properties.Resources.ResourceManager.GetString(OpType + "Template"); - if(string.IsNullOrEmpty(xamlTemplate)) + if (string.IsNullOrEmpty(xamlTemplate)) xamlTemplate = Properties.Resources.ResourceManager.GetString("CommonMiniTemplate"); spContent3.XamlText = xamlTemplate; } @@ -79,4 +71,4 @@ internal interface ISpecialWindowContentXamlTemplate { string XamlText { get; set; } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/ExampleModels/DataEdge.cs b/Examples/ShowcaseApp.WPF/ExampleModels/DataEdge.cs index d2114f1..a22ebb7 100644 --- a/Examples/ShowcaseApp.WPF/ExampleModels/DataEdge.cs +++ b/Examples/ShowcaseApp.WPF/ExampleModels/DataEdge.cs @@ -1,5 +1,4 @@ using System.ComponentModel; -using Westermo.GraphX; using System; using Westermo.GraphX.Measure; using Westermo.GraphX.Common.Models; @@ -15,13 +14,13 @@ public class DataEdge : EdgeBase, INotifyPropertyChanged public override Point[] RoutingPoints { get; set; } public DataEdge(DataVertex source, DataVertex target, double weight = 1) - : base(source, target, weight) - { + : base(source, target, weight) + { Angle = 90; - } + } public DataEdge() - : base(null, null, 1) + : base(null, null) { Angle = 90; } @@ -34,8 +33,18 @@ public DataEdge() /// Node main description (header) /// private string _text; - public string Text { get { return _text; } set { _text = value; OnPropertyChanged("Text"); } } - public string ToolTipText {get; set; } + + public string Text + { + get => _text; + set + { + _text = value; + OnPropertyChanged("Text"); + } + } + + public string ToolTipText { get; set; } public override string ToString() { @@ -46,8 +55,7 @@ public override string ToString() public void OnPropertyChanged(string name) { - if (PropertyChanged != null) - PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name)); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/ExampleModels/DataVertex.cs b/Examples/ShowcaseApp.WPF/ExampleModels/DataVertex.cs index f1f4fea..5e5389e 100644 --- a/Examples/ShowcaseApp.WPF/ExampleModels/DataVertex.cs +++ b/Examples/ShowcaseApp.WPF/ExampleModels/DataVertex.cs @@ -2,9 +2,9 @@ namespace ShowcaseApp.WPF { - public class DataVertex: VertexBase + public class DataVertex(string text = "") : VertexBase { - public string Text { get; set; } + public string Text { get; set; } = string.IsNullOrEmpty(text) ? "New Vertex" : text; public string Name { get; set; } public string Profession { get; set; } public string Gender { get; set; } @@ -29,10 +29,5 @@ public override string ToString() public DataVertex():this(string.Empty) { } - - public DataVertex(string text = "") - { - Text = string.IsNullOrEmpty(text) ? "New Vertex" : text; - } } } diff --git a/Examples/ShowcaseApp.WPF/ExampleModels/ExampleExternalEdgeRoutingAlgorithm.cs b/Examples/ShowcaseApp.WPF/ExampleModels/ExampleExternalEdgeRoutingAlgorithm.cs index d8cf4c8..d8bf4ca 100644 --- a/Examples/ShowcaseApp.WPF/ExampleModels/ExampleExternalEdgeRoutingAlgorithm.cs +++ b/Examples/ShowcaseApp.WPF/ExampleModels/ExampleExternalEdgeRoutingAlgorithm.cs @@ -15,8 +15,8 @@ public void Compute(CancellationToken cancellationToken) public IDictionary VertexPositions { get; set; } - readonly Dictionary _edgeRoutes = new Dictionary(); - public IDictionary EdgeRoutes { get { return _edgeRoutes; }} + private readonly Dictionary _edgeRoutes = []; + public IDictionary EdgeRoutes => _edgeRoutes; public Point[] ComputeSingle(TEdge edge) { return null; } diff --git a/Examples/ShowcaseApp.WPF/ExampleModels/ExampleExternalLayoutAlgorithm.cs b/Examples/ShowcaseApp.WPF/ExampleModels/ExampleExternalLayoutAlgorithm.cs index 3714367..c2ad1a8 100644 --- a/Examples/ShowcaseApp.WPF/ExampleModels/ExampleExternalLayoutAlgorithm.cs +++ b/Examples/ShowcaseApp.WPF/ExampleModels/ExampleExternalLayoutAlgorithm.cs @@ -13,12 +13,10 @@ Also shows how to use internal algorithms inside the external one. */ namespace ShowcaseApp.WPF { - public class ExampleExternalLayoutAlgorithm: IExternalLayout + public class ExampleExternalLayoutAlgorithm(IMutableBidirectionalGraph graph) + : IExternalLayout { - public bool SupportsObjectFreeze - { - get { return true; } - } + public bool SupportsObjectFreeze => true; public void ResetGraph(IEnumerable vertices, IEnumerable edges) { @@ -27,11 +25,7 @@ public void ResetGraph(IEnumerable vertices, IEnumerable e _graph.AddEdgeRange(edges); } - private IMutableBidirectionalGraph _graph; - public ExampleExternalLayoutAlgorithm(IMutableBidirectionalGraph graph) - { - _graph = graph; - } + private IMutableBidirectionalGraph _graph = graph; public void Compute(CancellationToken cancellationToken) { @@ -45,17 +39,11 @@ public void Compute(CancellationToken cancellationToken) _vertexPositions = algo.VertexPositions; } - IDictionary _vertexPositions = new Dictionary(); - public IDictionary VertexPositions - { - get { return _vertexPositions; } - } + private IDictionary _vertexPositions = new Dictionary(); + public IDictionary VertexPositions => _vertexPositions; public IDictionary VertexSizes { get; set; } - public bool NeedVertexSizes - { - get { return true; } - } + public bool NeedVertexSizes => true; } } diff --git a/Examples/ShowcaseApp.WPF/ExampleModels/GraphAreaExample.cs b/Examples/ShowcaseApp.WPF/ExampleModels/GraphAreaExample.cs index f1dd8b9..93ed29a 100644 --- a/Examples/ShowcaseApp.WPF/ExampleModels/GraphAreaExample.cs +++ b/Examples/ShowcaseApp.WPF/ExampleModels/GraphAreaExample.cs @@ -1,4 +1,3 @@ -using Westermo.GraphX; using Westermo.GraphX.Controls; using QuikGraph; diff --git a/Examples/ShowcaseApp.WPF/ExampleModels/OrthEr.cs b/Examples/ShowcaseApp.WPF/ExampleModels/OrthEr.cs index c02689e..877f1fb 100644 --- a/Examples/ShowcaseApp.WPF/ExampleModels/OrthEr.cs +++ b/Examples/ShowcaseApp.WPF/ExampleModels/OrthEr.cs @@ -1,25 +1,23 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Threading; -using Westermo.GraphX.Measure; +using QuikGraph; using Westermo.GraphX.Common.Interfaces; using Westermo.GraphX.Logic.Algorithms.EdgeRouting; -using QuikGraph; +using Westermo.GraphX.Measure; -namespace ShowcaseApp.WPF.ExampleModels +namespace ShowcaseApp.WPF { - public class OrthEr : EdgeRoutingAlgorithmBase + public class OrthEr( + TGraph graph, + IDictionary vertexPositions, + IDictionary vertexSizes, + IEdgeRoutingParameters parameters = null) + : EdgeRoutingAlgorithmBase(graph, vertexPositions, vertexSizes, parameters) where TGraph : class, IMutableBidirectionalGraph where TEdge : class, IGraphXEdge where TVertex : class, IGraphXVertex { - - public OrthEr(TGraph graph, IDictionary vertexPositions, IDictionary vertexSizes, IEdgeRoutingParameters parameters = null) : - base(graph, vertexPositions, vertexSizes, parameters) - { - - } - - public override void Compute(CancellationToken cancellationToken) { foreach (var edge in Graph.Edges) @@ -29,18 +27,17 @@ public override void Compute(CancellationToken cancellationToken) var sourceSize = VertexSizes[edge.Source]; var targetSize = VertexSizes[edge.Target]; - if (sourcePosition.X != targetPosition.X ) + if (Math.Abs(sourcePosition.X - targetPosition.X) > 1e-12) { EdgeRoutes.Add( edge, - new[] - { + [ new Point(0, 0), - new Point(targetPosition.X + targetSize.Width / 2, sourcePosition.Y + sourceSize.Height / 2), + new Point(targetPosition.X + targetSize.Width / 2, + sourcePosition.Y + sourceSize.Height / 2), new Point(0, 0) - }); + ]); } - } } @@ -53,4 +50,4 @@ public override Point[] ComputeSingle(TEdge edge) return null; } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/External/WindowGlow/GlowManager.cs b/Examples/ShowcaseApp.WPF/External/WindowGlow/GlowManager.cs index a82f4b5..3476636 100644 --- a/Examples/ShowcaseApp.WPF/External/WindowGlow/GlowManager.cs +++ b/Examples/ShowcaseApp.WPF/External/WindowGlow/GlowManager.cs @@ -4,113 +4,106 @@ using System.Windows; using System.Windows.Media; -namespace WindowGlows +namespace ShowcaseApp.WPF.External.WindowGlow { /// /// Contains static methods for making s glow. /// public static class GlowManager { - static readonly DependencyProperty GlowInfoProperty = - DependencyProperty.RegisterAttached( "GlowInfo", - typeof(GlowInfo), - typeof(GlowManager) ); + private static readonly DependencyProperty GlowInfoProperty = + DependencyProperty.RegisterAttached("GlowInfo", + typeof(GlowInfo), + typeof(GlowManager)); /// /// Identifies the ActiveGlowBrush attached property. /// public static readonly DependencyProperty ActiveGlowBrushProperty = - DependencyProperty.RegisterAttached( "ActiveGlowBrush", - typeof(Brush), - typeof(GlowManager), - new FrameworkPropertyMetadata( - new SolidColorBrush( - Color.FromArgb( 0xff, 0x00, 0x7a, 0xcc ) ) ) ); + DependencyProperty.RegisterAttached("ActiveGlowBrush", + typeof(Brush), + typeof(GlowManager), + new FrameworkPropertyMetadata( + new SolidColorBrush( + Color.FromArgb(0xff, 0x00, 0x7a, 0xcc)))); /// /// Identifies the InactiveGlowBrush attached property. /// public static readonly DependencyProperty InactiveGlowBrushProperty = - DependencyProperty.RegisterAttached( "InactiveGlowBrush", - typeof(Brush), - typeof(GlowManager), - new FrameworkPropertyMetadata( - new SolidColorBrush( Colors.Black ) { Opacity = 0.25 } ) ); + DependencyProperty.RegisterAttached("InactiveGlowBrush", + typeof(Brush), + typeof(GlowManager), + new FrameworkPropertyMetadata( + new SolidColorBrush(Colors.Black) { Opacity = 0.25 })); /// /// Identifies the EnableGlow attached property /// public static readonly DependencyProperty EnableGlowProperty = - DependencyProperty.RegisterAttached( "EnableGlow", - typeof(bool), - typeof(GlowManager), - new FrameworkPropertyMetadata( ( d, e ) => - { - if ( !DesignerProperties.GetIsInDesignMode( new DependencyObject() ) ) - { - if ( (bool)e.NewValue == true ) - Assign( (Window)d ); - else - Unassign( (Window)d ); - } - } ) ); + DependencyProperty.RegisterAttached("EnableGlow", + typeof(bool), + typeof(GlowManager), + new FrameworkPropertyMetadata((d, e) => + { + if (!DesignerProperties.GetIsInDesignMode(new DependencyObject())) + { + if ((bool)e.NewValue) + Assign((Window)d); + else + Unassign((Window)d); + } + })); - static Action assignGlows = window => + private static readonly Action assignGlows = window => { - if ( GetGlowInfo( window ) != null ) - throw new InvalidOperationException( "Glows have already been assigned." ); - GlowInfo glowInfo = new GlowInfo(); - glowInfo.glows.Add( new GlowWindow { Location = Location.Left } ); - glowInfo.glows.Add( new GlowWindow { Location = Location.Top } ); - glowInfo.glows.Add( new GlowWindow { Location = Location.Right } ); - glowInfo.glows.Add( new GlowWindow { Location = Location.Bottom } ); - foreach ( GlowWindow glow in glowInfo.glows ) + if (GetGlowInfo(window) != null) + throw new InvalidOperationException("Glows have already been assigned."); + var glowInfo = new GlowInfo(); + glowInfo.glows.Add(new GlowWindow { Location = Location.Left }); + glowInfo.glows.Add(new GlowWindow { Location = Location.Top }); + glowInfo.glows.Add(new GlowWindow { Location = Location.Right }); + glowInfo.glows.Add(new GlowWindow { Location = Location.Bottom }); + foreach (var glow in glowInfo.glows) { glow.Owner = window; glow.OwnerChanged(); } - SetGlowInfo( window, glowInfo ); + + SetGlowInfo(window, glowInfo); }; - static bool Assign( Window window ) + private static void Assign(Window window) { - if ( window == null ) - throw new ArgumentNullException( "window" ); - if ( GetGlowInfo( window ) != null ) - return false; - else if ( !window.IsLoaded ) - window.SourceInitialized += delegate - { - assignGlows( window ); - }; + ArgumentNullException.ThrowIfNull(window); + if (GetGlowInfo(window) != null) + return; + if (!window.IsLoaded) + window.SourceInitialized += delegate { assignGlows(window); }; else { - assignGlows( window ); + assignGlows(window); } - return true; } - static bool Unassign( Window window ) + private static void Unassign(Window window) { - GlowInfo info = GetGlowInfo( window ); - if ( info == null ) - return false; - else + var info = GetGlowInfo(window); + if (info == null) + return; + foreach (var glow in info.glows) { - foreach ( GlowWindow glow in info.glows ) + try { - try - { - glow.Close(); - } - catch - { - // Do nothing - } + glow.Close(); + } + catch + { + // Do nothing } - SetGlowInfo( window, null ); } - return true; + + SetGlowInfo(window, null); } /// @@ -120,9 +113,9 @@ static bool Unassign( Window window ) /// The brush for the glow when the is active. [Category("Brush")] [AttachedPropertyBrowsableForType(typeof(Window))] - public static Brush GetActiveGlowBrush( Window window ) + public static Brush GetActiveGlowBrush(Window window) { - return (Brush)window.GetValue( ActiveGlowBrushProperty ); + return (Brush)window.GetValue(ActiveGlowBrushProperty); } /// @@ -130,9 +123,9 @@ public static Brush GetActiveGlowBrush( Window window ) /// /// The . /// The for the glow when the is active. - public static void SetActiveGlowBrush( Window window, Brush value ) + public static void SetActiveGlowBrush(Window window, Brush value) { - window.SetValue( ActiveGlowBrushProperty, value ); + window.SetValue(ActiveGlowBrushProperty, value); } /// @@ -142,9 +135,9 @@ public static void SetActiveGlowBrush( Window window, Brush value ) /// The for the glow when the is inactive. [Category("Brush")] [AttachedPropertyBrowsableForType(typeof(Window))] - public static Brush GetInactiveGlowBrush( Window window ) + public static Brush GetInactiveGlowBrush(Window window) { - return (Brush)window.GetValue( InactiveGlowBrushProperty ); + return (Brush)window.GetValue(InactiveGlowBrushProperty); } /// @@ -152,9 +145,9 @@ public static Brush GetInactiveGlowBrush( Window window ) /// /// The . /// The for the glow when the is inactive. - public static void SetInactiveGlowBrush( Window window, Brush value ) + public static void SetInactiveGlowBrush(Window window, Brush value) { - window.SetValue( InactiveGlowBrushProperty, value ); + window.SetValue(InactiveGlowBrushProperty, value); } /// @@ -164,9 +157,9 @@ public static void SetInactiveGlowBrush( Window window, Brush value ) /// Whether glows are enabled for the . [Category("Appearance")] [AttachedPropertyBrowsableForType(typeof(Window))] - public static bool GetEnableGlow( Window window ) + public static bool GetEnableGlow(Window window) { - return (bool)window.GetValue( EnableGlowProperty ); + return (bool)window.GetValue(EnableGlowProperty); } /// @@ -174,24 +167,24 @@ public static bool GetEnableGlow( Window window ) /// /// The . /// Whether glows are enabled for the . - public static void SetEnableGlow( Window window, bool value ) + public static void SetEnableGlow(Window window, bool value) { - window.SetValue( EnableGlowProperty, value ); + window.SetValue(EnableGlowProperty, value); } - internal static GlowInfo GetGlowInfo( Window window ) + internal static GlowInfo GetGlowInfo(Window window) { - return (GlowInfo)window.GetValue( GlowInfoProperty ); + return (GlowInfo)window.GetValue(GlowInfoProperty); } - internal static void SetGlowInfo( Window window, GlowInfo info ) + internal static void SetGlowInfo(Window window, GlowInfo info) { - window.SetValue( GlowInfoProperty, info ); + window.SetValue(GlowInfoProperty, info); } } - class GlowInfo + internal class GlowInfo { - public readonly Collection glows = new Collection(); + public readonly Collection glows = []; } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/External/WindowGlow/GlowWindow.cs b/Examples/ShowcaseApp.WPF/External/WindowGlow/GlowWindow.cs index 67e3159..57a287b 100644 --- a/Examples/ShowcaseApp.WPF/External/WindowGlow/GlowWindow.cs +++ b/Examples/ShowcaseApp.WPF/External/WindowGlow/GlowWindow.cs @@ -5,19 +5,23 @@ using System.Windows.Input; using System.Windows.Interop; -namespace WindowGlows +namespace ShowcaseApp.WPF.External.WindowGlow { - enum Location + internal enum Location { - Left, Top, Right, Bottom + Left, + Top, + Right, + Bottom } [TemplatePart(Name = "PART_Glow", Type = typeof(Border))] - class GlowWindow : Window + internal class GlowWindow : Window { static GlowWindow() { - DefaultStyleKeyProperty.OverrideMetadata( typeof(GlowWindow), new FrameworkPropertyMetadata( typeof(GlowWindow) ) ); + DefaultStyleKeyProperty.OverrideMetadata(typeof(GlowWindow), + new FrameworkPropertyMetadata(typeof(GlowWindow))); } public double glowThickness = 40d, tolerance = 72d; @@ -26,12 +30,13 @@ static GlowWindow() public Action Update; public Func GetCursor; public Func GetHT; - Border Glow; - Func canResize; + private Border Glow; + private Func canResize; - public void NotifyResize( HT ht ) + public void NotifyResize(HT ht) { - NativeMethods.SendNotifyMessage( new WindowInteropHelper( Owner ).Handle, (int)WM.NCLBUTTONDOWN, (IntPtr)ht, IntPtr.Zero ); + NativeMethods.SendNotifyMessage(new WindowInteropHelper(Owner).Handle, (int)WM.NCLBUTTONDOWN, (IntPtr)ht, + IntPtr.Zero); } public GlowWindow() @@ -46,185 +51,180 @@ public GlowWindow() public override void OnApplyTemplate() { base.OnApplyTemplate(); - Glow = (Border)GetTemplateChild( "PART_Glow" ); - if ( Glow == null ) - throw new Exception( "PART_Glow not found." ); + Glow = (Border)GetTemplateChild("PART_Glow"); + if (Glow == null) + throw new Exception("PART_Glow not found."); Update(); } - protected override void OnSourceInitialized( EventArgs e ) + protected override void OnSourceInitialized(EventArgs e) { - base.OnSourceInitialized( e ); - IntPtr hwnd = new WindowInteropHelper( this ).Handle; - int ws_ex = NativeMethods.GetWindowLong( hwnd, (int)GWL.EXSTYLE ); + base.OnSourceInitialized(e); + var hwnd = new WindowInteropHelper(this).Handle; + var ws_ex = NativeMethods.GetWindowLong(hwnd, (int)GWL.EXSTYLE); ws_ex |= (int)WS_EX.TOOLWINDOW; - NativeMethods.SetWindowLong( hwnd, (int)GWL.EXSTYLE, ws_ex ); - HwndSource.FromHwnd( hwnd ).AddHook( WinMain ); + NativeMethods.SetWindowLong(hwnd, (int)GWL.EXSTYLE, ws_ex); + HwndSource.FromHwnd(hwnd)?.AddHook(WinMain); } - public virtual IntPtr WinMain( IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled ) + public virtual IntPtr WinMain(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { - switch ( (WM)msg ) + switch ((WM)msg) { case WM.MOUSEACTIVATE: - { - handled = true; - return new IntPtr( 3 ); // MA_NOACTIVATE - } + { + handled = true; + return new IntPtr(3); // MA_NOACTIVATE + } case WM.NCHITTEST: + { + if (canResize()) { - if ( canResize() ) - { - Point ptScreen = NativeMethods.LPARAMTOPOINT( lParam ); - Point ptClient = PointFromScreen( ptScreen ); - Cursor = GetCursor( ptClient ); - } - break; + var ptScreen = NativeMethods.LPARAMTOPOINT(lParam); + var ptClient = PointFromScreen(ptScreen); + Cursor = GetCursor(ptClient); } + + break; + } case WM.LBUTTONDOWN: - { - POINT ptScreenWin32; - NativeMethods.GetCursorPos( out ptScreenWin32 ); - Point ptScreen = new Point( ptScreenWin32.x, ptScreenWin32.y ); - Point ptClient = PointFromScreen( ptScreen ); - HT result = GetHT( ptClient ); - IntPtr ownerHwnd = new WindowInteropHelper( Owner ).Handle; - NativeMethods.SendNotifyMessage( ownerHwnd, (int)WM.NCLBUTTONDOWN, (IntPtr)result, IntPtr.Zero ); - break; - } + { + POINT ptScreenWin32; + NativeMethods.GetCursorPos(out ptScreenWin32); + var ptScreen = new Point(ptScreenWin32.x, ptScreenWin32.y); + var ptClient = PointFromScreen(ptScreen); + var result = GetHT(ptClient); + var ownerHwnd = new WindowInteropHelper(Owner).Handle; + NativeMethods.SendNotifyMessage(ownerHwnd, (int)WM.NCLBUTTONDOWN, (IntPtr)result, IntPtr.Zero); + break; + } } + return IntPtr.Zero; } public void OwnerChanged() { - canResize = () => Owner.ResizeMode == ResizeMode.CanResize ? true : - Owner.ResizeMode == ResizeMode.CanResizeWithGrip ? true : false; + canResize = () => + Owner.ResizeMode is ResizeMode.CanResize or ResizeMode.CanResizeWithGrip; - switch ( Location ) + switch (Location) { case Location.Left: - { - GetCursor = pt => - new Rect( new Point( 0, 0 ), new Size( ActualWidth, tolerance ) ).Contains( pt ) ? - Cursors.SizeNWSE : - new Rect( new Point( 0, ActualHeight - tolerance ), new Size( ActualWidth, tolerance ) ).Contains( pt ) ? - Cursors.SizeNESW : - Cursors.SizeWE; + { + GetCursor = pt => + new Rect(new Point(0, 0), new Size(ActualWidth, tolerance)).Contains(pt) ? Cursors.SizeNWSE : + new Rect(new Point(0, ActualHeight - tolerance), new Size(ActualWidth, tolerance)) + .Contains(pt) ? Cursors.SizeNESW : + Cursors.SizeWE; - GetHT = pt => new Rect( new Point( 0, 0 ), new Size( ActualWidth, tolerance ) ).Contains( pt ) ? - HT.TOPLEFT : - new Rect( new Point( 0, ActualHeight - tolerance ), new Size( ActualWidth, tolerance ) ).Contains( pt ) ? - HT.BOTTOMLEFT : - HT.LEFT; + GetHT = pt => new Rect(new Point(0, 0), new Size(ActualWidth, tolerance)).Contains(pt) + ? HT.TOPLEFT + : new Rect(new Point(0, ActualHeight - tolerance), new Size(ActualWidth, tolerance)) + .Contains(pt) + ? HT.BOTTOMLEFT + : HT.LEFT; - Update = delegate - { - if ( Glow != null ) - Glow.Margin = new Thickness( glowThickness, glowThickness, -glowThickness, glowThickness ); - Left = Owner.Left - glowThickness; - Top = Owner.Top - glowThickness; - Width = glowThickness; - Height = Owner.ActualHeight + glowThickness * 2; - }; - break; - } + Update = delegate + { + if (Glow != null) + Glow.Margin = new Thickness(glowThickness, glowThickness, -glowThickness, glowThickness); + Left = Owner.Left - glowThickness; + Top = Owner.Top - glowThickness; + Width = glowThickness; + Height = Owner.ActualHeight + glowThickness * 2; + }; + break; + } case Location.Top: - { - GetCursor = pt => - new Rect( new Point( 0, 0 ), new Size( tolerance, glowThickness ) ).Contains( pt ) ? - Cursors.SizeNWSE : - new Rect( new Point( ActualWidth - tolerance, 0 ), new Size( tolerance, ActualHeight ) ).Contains( pt ) ? - Cursors.SizeNESW : - Cursors.SizeNS; + { + GetCursor = pt => + new Rect(new Point(0, 0), new Size(tolerance, glowThickness)).Contains(pt) ? Cursors.SizeNWSE : + new Rect(new Point(ActualWidth - tolerance, 0), new Size(tolerance, ActualHeight)) + .Contains(pt) ? Cursors.SizeNESW : + Cursors.SizeNS; - GetHT = pt => - new Rect( new Point( 0, 0 ), new Size( tolerance, glowThickness ) ).Contains( pt ) ? - HT.TOPLEFT : - new Rect( new Point( ActualWidth - tolerance, 0 ), new Size( tolerance, ActualHeight ) ).Contains( pt ) ? - HT.TOPRIGHT : - HT.TOP; + GetHT = pt => + new Rect(new Point(0, 0), new Size(tolerance, glowThickness)).Contains(pt) ? HT.TOPLEFT : + new Rect(new Point(ActualWidth - tolerance, 0), new Size(tolerance, ActualHeight)) + .Contains(pt) ? HT.TOPRIGHT : + HT.TOP; - Update = delegate - { - if ( Glow != null ) - Glow.Margin = new Thickness( glowThickness, glowThickness, glowThickness, -glowThickness ); - Left = Owner.Left - glowThickness; - Top = Owner.Top - glowThickness; - Width = Owner.ActualWidth + glowThickness * 2; - Height = glowThickness; - }; - break; - } + Update = delegate + { + if (Glow != null) + Glow.Margin = new Thickness(glowThickness, glowThickness, glowThickness, -glowThickness); + Left = Owner.Left - glowThickness; + Top = Owner.Top - glowThickness; + Width = Owner.ActualWidth + glowThickness * 2; + Height = glowThickness; + }; + break; + } case Location.Right: - { - GetCursor = pt => - new Rect( new Point( 0, 0 ), new Size( ActualWidth, tolerance ) ).Contains( pt ) ? - Cursors.SizeNESW : - new Rect( new Point( 0, ActualHeight - tolerance ), new Size( ActualWidth, tolerance ) ).Contains( pt ) ? - Cursors.SizeNWSE : - Cursors.SizeWE; + { + GetCursor = pt => + new Rect(new Point(0, 0), new Size(ActualWidth, tolerance)).Contains(pt) ? Cursors.SizeNESW : + new Rect(new Point(0, ActualHeight - tolerance), new Size(ActualWidth, tolerance)) + .Contains(pt) ? Cursors.SizeNWSE : + Cursors.SizeWE; - GetHT = pt => new Rect( new Point( 0, 0 ), new Size( ActualWidth, tolerance ) ).Contains( pt ) ? - HT.TOPRIGHT : - new Rect( new Point( 0, ActualHeight - tolerance ), new Size( ActualWidth, tolerance ) ).Contains( pt ) ? - HT.BOTTOMRIGHT : - HT.RIGHT; + GetHT = pt => new Rect(new Point(0, 0), new Size(ActualWidth, tolerance)).Contains(pt) + ? HT.TOPRIGHT + : new Rect(new Point(0, ActualHeight - tolerance), new Size(ActualWidth, tolerance)) + .Contains(pt) + ? HT.BOTTOMRIGHT + : HT.RIGHT; - Update = delegate - { - if ( Glow != null ) - Glow.Margin = new Thickness( -glowThickness, glowThickness, glowThickness, glowThickness ); - Left = Owner.Left + Owner.ActualWidth; - Top = Owner.Top - glowThickness; - Width = glowThickness; - Height = Owner.ActualHeight + glowThickness * 2; - }; - break; - } + Update = delegate + { + if (Glow != null) + Glow.Margin = new Thickness(-glowThickness, glowThickness, glowThickness, glowThickness); + Left = Owner.Left + Owner.ActualWidth; + Top = Owner.Top - glowThickness; + Width = glowThickness; + Height = Owner.ActualHeight + glowThickness * 2; + }; + break; + } case Location.Bottom: - { - GetCursor = pt => - new Rect( new Point( 0, 0 ), new Size( tolerance, glowThickness ) ).Contains( pt ) ? - Cursors.SizeNESW : - new Rect( new Point( ActualWidth - tolerance, 0 ), new Size( tolerance, ActualHeight ) ).Contains( pt ) ? - Cursors.SizeNWSE : - Cursors.SizeNS; + { + GetCursor = pt => + new Rect(new Point(0, 0), new Size(tolerance, glowThickness)).Contains(pt) ? Cursors.SizeNESW : + new Rect(new Point(ActualWidth - tolerance, 0), new Size(tolerance, ActualHeight)) + .Contains(pt) ? Cursors.SizeNWSE : + Cursors.SizeNS; - GetHT = pt => - new Rect( new Point( 0, 0 ), new Size( tolerance, glowThickness ) ).Contains( pt ) ? - HT.BOTTOMLEFT : - new Rect( new Point( ActualWidth - tolerance, 0 ), new Size( tolerance, ActualHeight ) ).Contains( pt ) ? - HT.BOTTOMRIGHT : - HT.BOTTOM; + GetHT = pt => + new Rect(new Point(0, 0), new Size(tolerance, glowThickness)).Contains(pt) ? HT.BOTTOMLEFT : + new Rect(new Point(ActualWidth - tolerance, 0), new Size(tolerance, ActualHeight)) + .Contains(pt) ? HT.BOTTOMRIGHT : + HT.BOTTOM; - Update = delegate - { - if ( Glow != null ) - Glow.Margin = new Thickness( glowThickness, -glowThickness, glowThickness, glowThickness ); - Left = Owner.Left - glowThickness; - Top = Owner.Top + Owner.ActualHeight; - Width = Owner.ActualWidth + glowThickness * 2; - Height = glowThickness; - }; - break; - } + Update = delegate + { + if (Glow != null) + Glow.Margin = new Thickness(glowThickness, -glowThickness, glowThickness, glowThickness); + Left = Owner.Left - glowThickness; + Top = Owner.Top + Owner.ActualHeight; + Width = Owner.ActualWidth + glowThickness * 2; + Height = glowThickness; + }; + break; + } + default: + throw new ArgumentOutOfRangeException(); } - Owner.LocationChanged += delegate - { - Update(); - }; - Owner.SizeChanged += delegate - { - Update(); - }; + + Owner.LocationChanged += delegate { Update(); }; + Owner.SizeChanged += delegate { Update(); }; Owner.StateChanged += delegate { - switch ( Owner.WindowState ) + switch (Owner.WindowState) { case WindowState.Maximized: Hide(); @@ -237,20 +237,20 @@ public void OwnerChanged() }; Owner.Activated += delegate { - Binding activeBrushBinding = new Binding(); - activeBrushBinding.Path = new PropertyPath( GlowManager.ActiveGlowBrushProperty ); + var activeBrushBinding = new Binding(); + activeBrushBinding.Path = new PropertyPath(GlowManager.ActiveGlowBrushProperty); activeBrushBinding.Source = Owner; - SetBinding( ForegroundProperty, activeBrushBinding ); + SetBinding(ForegroundProperty, activeBrushBinding); }; Owner.Deactivated += delegate { - Binding activeBrushBinding = new Binding(); - activeBrushBinding.Path = new PropertyPath( GlowManager.InactiveGlowBrushProperty ); + var activeBrushBinding = new Binding(); + activeBrushBinding.Path = new PropertyPath(GlowManager.InactiveGlowBrushProperty); activeBrushBinding.Source = Owner; - SetBinding( ForegroundProperty, activeBrushBinding ); + SetBinding(ForegroundProperty, activeBrushBinding); }; Update(); Show(); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/External/WindowGlow/Win32.cs b/Examples/ShowcaseApp.WPF/External/WindowGlow/Win32.cs index f4ebd71..2a232ed 100644 --- a/Examples/ShowcaseApp.WPF/External/WindowGlow/Win32.cs +++ b/Examples/ShowcaseApp.WPF/External/WindowGlow/Win32.cs @@ -2,9 +2,9 @@ using System.Runtime.InteropServices; using System.Windows; -namespace WindowGlows +namespace ShowcaseApp.WPF.External.WindowGlow { - enum HT + internal enum HT { BORDER = 18, BOTTOM = 15, @@ -17,7 +17,7 @@ enum HT TOPRIGHT = 14 } - enum WM + internal enum WM { NCLBUTTONDOWN = 0x00A1, MOUSEACTIVATE = 0x0021, @@ -25,17 +25,17 @@ enum WM NCHITTEST = 0x0084 } - enum GWL + internal enum GWL { EXSTYLE = -20 } - enum WS_EX + internal enum WS_EX { TOOLWINDOW = 0x00000080 } - class NativeMethods + internal class NativeMethods { public static Func MAKELPARAM = ( wLow, wHigh ) => { @@ -63,7 +63,7 @@ class NativeMethods } [StructLayout(LayoutKind.Sequential)] - struct POINT + internal struct POINT { public int x; public int y; diff --git a/Examples/ShowcaseApp.WPF/FileSerialization/FileServiceProviderWPF.cs b/Examples/ShowcaseApp.WPF/FileSerialization/FileServiceProviderWPF.cs index 92b9135..663ab48 100644 --- a/Examples/ShowcaseApp.WPF/FileSerialization/FileServiceProviderWPF.cs +++ b/Examples/ShowcaseApp.WPF/FileSerialization/FileServiceProviderWPF.cs @@ -17,7 +17,7 @@ public static class FileServiceProviderWpf /// Data classes list public static void SerializeDataToFile(string filename, List modelsList) { - using (FileStream stream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read)) + using (var stream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read)) { SerializeDataToStream(stream, modelsList); } @@ -29,7 +29,7 @@ public static void SerializeDataToFile(string filename, ListFile name public static List DeserializeDataFromFile(string filename) { - using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (var stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { return DeserializeDataFromStream(stream); } diff --git a/Examples/ShowcaseApp.WPF/FileSerialization/YAXPointArraySerializer.cs b/Examples/ShowcaseApp.WPF/FileSerialization/YAXPointArraySerializer.cs index 899323a..414df71 100644 --- a/Examples/ShowcaseApp.WPF/FileSerialization/YAXPointArraySerializer.cs +++ b/Examples/ShowcaseApp.WPF/FileSerialization/YAXPointArraySerializer.cs @@ -1,7 +1,7 @@ using System; +using System.Globalization; using System.Linq; using System.Text; -using System.Xml.Linq; using Westermo.GraphX.Measure; using YAXLib; using YAXLib.Customization; @@ -10,20 +10,22 @@ namespace ShowcaseApp.WPF.FileSerialization { public sealed class YAXPointArraySerializer : ICustomSerializer { + private static readonly char[] separator = ['~']; private Point[] Deserialize(string str) { if (string.IsNullOrEmpty(str)) return null; - var arr = str.Split(new char[] { '~' }); + var arr = str.Split(separator); var ptlist = new Point[arr.Length]; - int cnt = 0; + var cnt = 0; foreach (var item in arr) { - var res = item.Split(new char[] { '|' }); + var res = item.Split(new[] { '|' }); if (res.Length == 2) ptlist[cnt] = new Point(Convert.ToDouble(res[0]), Convert.ToDouble(res[1])); else ptlist[cnt] = new Point(); cnt++; } + return ptlist; } @@ -34,17 +36,21 @@ private string Serialize(Point[] list) { var last = list.Last(); foreach (var item in list) - sb.Append(string.Format("{0}|{1}{2}", item.X.ToString(), item.Y.ToString(), (item != last ? "~" : ""))); + sb.Append( + $"{item.X.ToString(CultureInfo.InvariantCulture)}|{item.Y.ToString(CultureInfo.InvariantCulture)}{(item != last ? "~" : "")}"); } + return sb.ToString(); } - public Point[] DeserializeFromAttribute(System.Xml.Linq.XAttribute attrib, ISerializationContext serializationContext) + public Point[] DeserializeFromAttribute(System.Xml.Linq.XAttribute attrib, + ISerializationContext serializationContext) { return Deserialize(attrib.Value); } - public Point[] DeserializeFromElement(System.Xml.Linq.XElement element, ISerializationContext serializationContext) + public Point[] DeserializeFromElement(System.Xml.Linq.XElement element, + ISerializationContext serializationContext) { return Deserialize(element.Value); } @@ -54,12 +60,14 @@ public Point[] DeserializeFromValue(string value, ISerializationContext serializ return Deserialize(value); } - public void SerializeToAttribute(Point[] objectToSerialize, System.Xml.Linq.XAttribute attrToFill, ISerializationContext serializationContext) + public void SerializeToAttribute(Point[] objectToSerialize, System.Xml.Linq.XAttribute attrToFill, + ISerializationContext serializationContext) { attrToFill.Value = Serialize(objectToSerialize); } - public void SerializeToElement(Point[] objectToSerialize, System.Xml.Linq.XElement elemToFill, ISerializationContext serializationContext) + public void SerializeToElement(Point[] objectToSerialize, System.Xml.Linq.XElement elemToFill, + ISerializationContext serializationContext) { elemToFill.Value = Serialize(objectToSerialize); } @@ -69,4 +77,4 @@ public string SerializeToValue(Point[] objectToSerialize, ISerializationContext return Serialize(objectToSerialize); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/FileSerialization/YAXPointSerializer.cs b/Examples/ShowcaseApp.WPF/FileSerialization/YAXPointSerializer.cs index 585c42a..aaaed42 100644 --- a/Examples/ShowcaseApp.WPF/FileSerialization/YAXPointSerializer.cs +++ b/Examples/ShowcaseApp.WPF/FileSerialization/YAXPointSerializer.cs @@ -1,26 +1,28 @@ using System; +using System.Globalization; using Westermo.GraphX.Measure; using YAXLib; using YAXLib.Customization; namespace ShowcaseApp.WPF.FileSerialization { - public sealed class YAXPointSerializer: ICustomSerializer + public sealed class YAXPointSerializer : ICustomSerializer { - private Point Deserialize(string str) { - var res = str.Split(new char[] { '|' }); + var res = str.Split(new[] { '|' }); if (res.Length == 2) return new Point(Convert.ToDouble(res[0]), Convert.ToDouble(res[1])); else return new Point(); } - public Point DeserializeFromAttribute(System.Xml.Linq.XAttribute attrib, ISerializationContext serializationContext) + public Point DeserializeFromAttribute(System.Xml.Linq.XAttribute attrib, + ISerializationContext serializationContext) { return Deserialize(attrib.Value); } - public Point DeserializeFromElement(System.Xml.Linq.XElement element, ISerializationContext serializationContext) + public Point DeserializeFromElement(System.Xml.Linq.XElement element, + ISerializationContext serializationContext) { return Deserialize(element.Value); } @@ -30,19 +32,24 @@ public Point DeserializeFromValue(string value, ISerializationContext serializat return Deserialize(value); } - public void SerializeToAttribute(Point objectToSerialize, System.Xml.Linq.XAttribute attrToFill, ISerializationContext serializationContext) + public void SerializeToAttribute(Point objectToSerialize, System.Xml.Linq.XAttribute attrToFill, + ISerializationContext serializationContext) { - attrToFill.Value = String.Format("{0}|{1}", objectToSerialize.X.ToString(), objectToSerialize.Y.ToString()); + attrToFill.Value = + $"{objectToSerialize.X.ToString(CultureInfo.InvariantCulture)}|{objectToSerialize.Y.ToString(CultureInfo.InvariantCulture)}"; } - public void SerializeToElement(Point objectToSerialize, System.Xml.Linq.XElement elemToFill, ISerializationContext serializationContext) + public void SerializeToElement(Point objectToSerialize, System.Xml.Linq.XElement elemToFill, + ISerializationContext serializationContext) { - elemToFill.Value = String.Format("{0}|{1}", objectToSerialize.X.ToString(), objectToSerialize.Y.ToString()); + elemToFill.Value = + $"{objectToSerialize.X.ToString(CultureInfo.InvariantCulture)}|{objectToSerialize.Y.ToString(CultureInfo.InvariantCulture)}"; } public string SerializeToValue(Point objectToSerialize, ISerializationContext serializationContext) { - return String.Format("{0}|{1}", objectToSerialize.X.ToString(), objectToSerialize.Y.ToString()); + return + $"{objectToSerialize.X.ToString(CultureInfo.InvariantCulture)}|{objectToSerialize.Y.ToString(CultureInfo.InvariantCulture)}"; } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/MainWindow.xaml.cs b/Examples/ShowcaseApp.WPF/MainWindow.xaml.cs index c84fda2..906f3e8 100644 --- a/Examples/ShowcaseApp.WPF/MainWindow.xaml.cs +++ b/Examples/ShowcaseApp.WPF/MainWindow.xaml.cs @@ -13,19 +13,21 @@ namespace ShowcaseApp.WPF /// /// Interaction logic for MainWindow.xaml /// - public partial class MainWindow : ModernWindow + public partial class MainWindow { public MainWindow() { InitializeComponent(); - Title = "Westermo GraphX for WPF showcase application v" + FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion; + Title = "Westermo GraphX for WPF showcase application v" + + FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion; #if DEBUG - var lg = new LinkGroup {DisplayName = "Debug"}; - lg.Links.Add(new Link { DisplayName = "Debug", Source = new Uri("Pages/Debug/DebugGraph.xaml", UriKind.Relative) }); + var lg = new LinkGroup { DisplayName = "Debug" }; + lg.Links.Add(new Link + { DisplayName = "Debug", Source = new Uri("Pages/Debug/DebugGraph.xaml", UriKind.Relative) }); MenuLinkGroups.Add(lg); #endif - this.CommandBindings.Add(new CommandBinding(LinkCommands.ShowMiniSpecialDialog, OnShowMiniSpecialDialog, OnCanShowMiniSpecialDialog)); - + CommandBindings.Add(new CommandBinding(LinkCommands.ShowMiniSpecialDialog, OnShowMiniSpecialDialog, + OnCanShowMiniSpecialDialog)); } private void OnShowMiniSpecialDialog(object sender, ExecutedRoutedEventArgs e) @@ -33,7 +35,7 @@ private void OnShowMiniSpecialDialog(object sender, ExecutedRoutedEventArgs e) var dlg = new ModernDialog { Title = "Help & code window", - Content = new SpecialWindowControl(e.Parameter), + Content = new SpecialWindowControl(e.Parameter), ResizeMode = ResizeMode.CanResize, MaxWidth = 1920, MaxHeight = 1080, @@ -42,12 +44,14 @@ private void OnShowMiniSpecialDialog(object sender, ExecutedRoutedEventArgs e) Width = 700, Height = 500, SizeToContent = SizeToContent.Manual, - + OkButton = + { + Content = "OK", + VerticalContentAlignment = VerticalAlignment.Center + } }; - dlg.OkButton.Content = "OK"; - dlg.OkButton.VerticalContentAlignment = VerticalAlignment.Center; //dlg.OkButton.FontWeight = FontWeights.Bold; - dlg.Buttons = new[] { dlg.OkButton }; + dlg.Buttons = [dlg.OkButton]; dlg.ShowDialog(); } @@ -56,4 +60,4 @@ private void OnCanShowMiniSpecialDialog(object sender, CanExecuteRoutedEventArgs e.CanExecute = true; } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Models/ColorModel.cs b/Examples/ShowcaseApp.WPF/Models/ColorModel.cs index 207f865..0100e9b 100644 --- a/Examples/ShowcaseApp.WPF/Models/ColorModel.cs +++ b/Examples/ShowcaseApp.WPF/Models/ColorModel.cs @@ -2,14 +2,9 @@ namespace ShowcaseApp.WPF.Models { - public class ColorModel + public class ColorModel(string text, Color color) { - public Color Color {get;set;} - public string Text { get; set; } - - public ColorModel(string text, Color color) - { - Text = text; Color = color; - } + public Color Color {get;set;} = color; + public string Text { get; set; } = text; } } diff --git a/Examples/ShowcaseApp.WPF/Models/EditorObjectManager.cs b/Examples/ShowcaseApp.WPF/Models/EditorObjectManager.cs index 16f0358..7b424f4 100644 --- a/Examples/ShowcaseApp.WPF/Models/EditorObjectManager.cs +++ b/Examples/ShowcaseApp.WPF/Models/EditorObjectManager.cs @@ -2,13 +2,12 @@ using System.Windows; using System.Windows.Media; using System.Windows.Shapes; -using Westermo.GraphX; using Westermo.GraphX.Controls; using Westermo.GraphX.Controls.Models; namespace ShowcaseApp.WPF.Models { - public class EditorObjectManager: IDisposable + public class EditorObjectManager : IDisposable { private GraphAreaExample _graphArea; private ZoomControl _zoomControl; @@ -27,15 +26,15 @@ public EditorObjectManager(GraphAreaExample graphArea, ZoomControl zc) }; } - public void CreateVirtualEdge(VertexControl source, Point mousePos) + public void CreateVirtualEdge(VertexControl source, Point mousePos) { - _edgeBp = new EdgeBlueprint(source, mousePos, (LinearGradientBrush)_rd["EdgeBrush"]); + _edgeBp = new EdgeBlueprint(source, (LinearGradientBrush)_rd["EdgeBrush"]); _graphArea.InsertCustomChildControl(0, _edgeBp.EdgePath); } - void _zoomControl_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) + private void _zoomControl_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) { - if(_edgeBp == null) return; + if (_edgeBp == null) return; var pos = _zoomControl.TranslatePoint(e.GetPosition(_zoomControl), _graphArea); pos.Offset(2, 2); _edgeBp.UpdateTargetPosition(pos); @@ -43,7 +42,7 @@ void _zoomControl_MouseMove(object sender, System.Windows.Input.MouseEventArgs e private void ClearEdgeBp() { - if(_edgeBp == null) return; + if (_edgeBp == null) return; _graphArea.RemoveCustomChildControl(_edgeBp.EdgePath); _edgeBp.Dispose(); _edgeBp = null; @@ -53,7 +52,7 @@ public void Dispose() { ClearEdgeBp(); _graphArea = null; - if(_zoomControl != null) + if (_zoomControl != null) _zoomControl.MouseMove -= _zoomControl_MouseMove; _zoomControl = null; _rd = null; @@ -65,20 +64,24 @@ public void DestroyVirtualEdge() } } - public class EdgeBlueprint: IDisposable + public class EdgeBlueprint : IDisposable { public VertexControl Source { get; set; } public Point TargetPos { get; set; } public Path EdgePath { get; set; } - public EdgeBlueprint(VertexControl source, Point targetPos, Brush brush) + public EdgeBlueprint(VertexControl source, Brush brush) { - EdgePath = new Path() { Stroke = brush, Data = new LineGeometry() }; + EdgePath = new Path + { + Stroke = brush, + Data = new LineGeometry() + }; Source = source; Source.PositionChanged += Source_PositionChanged; } - void Source_PositionChanged(object sender, VertexPositionEventArgs args) + private void Source_PositionChanged(object sender, VertexPositionEventArgs args) { UpdateGeometry(Source.GetCenterPosition(), TargetPos); } @@ -92,7 +95,7 @@ internal void UpdateTargetPosition(Point point) private void UpdateGeometry(Point start, Point end) { EdgePath.Data = new LineGeometry(start, end); - (EdgePath.Data as LineGeometry).Freeze(); + (EdgePath.Data as LineGeometry)?.Freeze(); } public void Dispose() @@ -101,4 +104,4 @@ public void Dispose() Source = null; } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Models/ImageLoader.cs b/Examples/ShowcaseApp.WPF/Models/ImageLoader.cs index 30eb6f4..e63f992 100644 --- a/Examples/ShowcaseApp.WPF/Models/ImageLoader.cs +++ b/Examples/ShowcaseApp.WPF/Models/ImageLoader.cs @@ -6,7 +6,7 @@ namespace ShowcaseApp.WPF.Models { public static class ImageLoader { - private static readonly List Images = new List(); + private static readonly List Images = []; static ImageLoader() { diff --git a/Examples/ShowcaseApp.WPF/Models/LinkCommands.cs b/Examples/ShowcaseApp.WPF/Models/LinkCommands.cs index e944eb6..3886b28 100644 --- a/Examples/ShowcaseApp.WPF/Models/LinkCommands.cs +++ b/Examples/ShowcaseApp.WPF/Models/LinkCommands.cs @@ -4,14 +4,11 @@ namespace ShowcaseApp.WPF.Models { public static class LinkCommands { - private static readonly RoutedUICommand ShowMiniSpecialDialogInternal = new RoutedUICommand("Show help", "ShowMiniSpecialDialog", typeof(LinkCommands)); + private static readonly RoutedUICommand ShowMiniSpecialDialogInternal = new("Show help", "ShowMiniSpecialDialog", typeof(LinkCommands)); /// /// Gets the navigate link routed command. /// - public static RoutedUICommand ShowMiniSpecialDialog - { - get { return ShowMiniSpecialDialogInternal; } - } + public static RoutedUICommand ShowMiniSpecialDialog => ShowMiniSpecialDialogInternal; } } diff --git a/Examples/ShowcaseApp.WPF/Models/ShadowChrome.cs b/Examples/ShowcaseApp.WPF/Models/ShadowChrome.cs index fe57d85..1531069 100644 --- a/Examples/ShowcaseApp.WPF/Models/ShadowChrome.cs +++ b/Examples/ShowcaseApp.WPF/Models/ShadowChrome.cs @@ -25,26 +25,26 @@ static ShadowChrome() protected override void OnRender(DrawingContext drawingContext) { // Calculate the size of the shadow - double shadowSize = Math.Min(Margin.Right, Margin.Bottom); + var shadowSize = Math.Min(Margin.Right, Margin.Bottom); // If there is no shadow, or it is bigger than the size of the child, then just return - if (shadowSize <= 0 || this.ActualWidth < shadowSize * 2 || this.ActualHeight < shadowSize * 2) + if (shadowSize <= 0 || ActualWidth < shadowSize * 2 || ActualHeight < shadowSize * 2) return; // Draw the background (this may show through rounded corners of the child object) - Rect backgroundRect = new Rect(shadowSize, shadowSize, this.ActualWidth - shadowSize, this.ActualHeight - shadowSize); + var backgroundRect = new Rect(shadowSize, shadowSize, ActualWidth - shadowSize, ActualHeight - shadowSize); drawingContext.DrawRectangle(backgroundBrush, null, backgroundRect); // Now draw the shadow gradients - Rect topRightRect = new Rect(this.ActualWidth, shadowSize, shadowSize, shadowSize); + var topRightRect = new Rect(ActualWidth, shadowSize, shadowSize, shadowSize); drawingContext.DrawRectangle(topRightBrush, null, topRightRect); - Rect rightRect = new Rect(this.ActualWidth, shadowSize * 2, shadowSize, this.ActualHeight - shadowSize * 2); + var rightRect = new Rect(ActualWidth, shadowSize * 2, shadowSize, ActualHeight - shadowSize * 2); drawingContext.DrawRectangle(rightBrush, null, rightRect); - Rect bottomRightRect = new Rect(this.ActualWidth, this.ActualHeight, shadowSize, shadowSize); + var bottomRightRect = new Rect(ActualWidth, ActualHeight, shadowSize, shadowSize); drawingContext.DrawRectangle(bottomRightBrush, null, bottomRightRect); - Rect bottomRect = new Rect(shadowSize * 2, this.ActualHeight, this.ActualWidth - shadowSize * 2, shadowSize); + var bottomRect = new Rect(shadowSize * 2, ActualHeight, ActualWidth - shadowSize * 2, shadowSize); drawingContext.DrawRectangle(bottomBrush, null, bottomRect); - Rect bottomLeftRect = new Rect(shadowSize, this.ActualHeight, shadowSize, shadowSize); + var bottomLeftRect = new Rect(shadowSize, ActualHeight, shadowSize, shadowSize); drawingContext.DrawRectangle(bottomLeftBrush, null, bottomLeftRect); } @@ -53,12 +53,14 @@ protected override void OnRender(DrawingContext drawingContext) private static void CreateBrushes() { // Get the colors for the shadow - Color shadowColor = Color.FromArgb(128, 0, 0, 0); - Color transparentColor = Color.FromArgb(16, 0, 0, 0); + var shadowColor = Color.FromArgb(128, 0, 0, 0); + var transparentColor = Color.FromArgb(16, 0, 0, 0); // Create a GradientStopCollection from these - GradientStopCollection gradient = new GradientStopCollection(2); - gradient.Add(new GradientStop(shadowColor, 0.5)); - gradient.Add(new GradientStop(transparentColor, 1.0)); + var gradient = new GradientStopCollection(2) + { + new GradientStop(shadowColor, 0.5), + new GradientStop(transparentColor, 1.0) + }; gradient.Freeze(); // Create the background brush backgroundBrush = new SolidColorBrush(shadowColor); diff --git a/Examples/ShowcaseApp.WPF/Models/ShowcaseHelper.cs b/Examples/ShowcaseApp.WPF/Models/ShowcaseHelper.cs index f4a46a3..b261f00 100644 --- a/Examples/ShowcaseApp.WPF/Models/ShowcaseHelper.cs +++ b/Examples/ShowcaseApp.WPF/Models/ShowcaseHelper.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using QuikGraph; namespace ShowcaseApp.WPF.Models @@ -12,14 +11,14 @@ static ShowcaseHelper() { GenerateData(DATASOURCE_SIZE); } - + /// /// General data source /// public static List DataSource { get; set; } public const int DATASOURCE_SIZE = 5000; - public static readonly Random Rand = new Random(Guid.NewGuid().GetHashCode()); + public static readonly Random Rand = new(Guid.NewGuid().GetHashCode()); private static void GenerateData(int count) { @@ -28,10 +27,12 @@ private static void GenerateData(int count) { list.Add(new DataItem { ID = i, Text = "Vertex " + i }); } + DataSource = list; } - public static void AddEdge(BidirectionalGraph graph, DataVertex source, DataVertex target, int? sourcePoint = null, int? targetPoint = null, int weight = 0) + public static void AddEdge(BidirectionalGraph graph, DataVertex source, DataVertex target, + int? sourcePoint = null, int? targetPoint = null, int weight = 0) { var edge = new DataEdge(source, target, weight) { @@ -39,20 +40,12 @@ public static void AddEdge(BidirectionalGraph graph, DataV Text = string.Empty, SourceConnectionPointId = sourcePoint, TargetConnectionPointId = targetPoint, - ToolTipText = "Label "+ source.ID + ToolTipText = "Label " + source.ID }; graph.AddEdge(edge); } - public static DataEdge GenerateEdge(DataVertex source, DataVertex target, int weight = 0) - { - return new DataEdge(source, target, weight) - { - Text = string.Empty - }; - } - #region GenerateDataGraph /// @@ -60,12 +53,13 @@ public static DataEdge GenerateEdge(DataVertex source, DataVertex target, int we /// /// Items count /// + /// public static GraphExample GenerateDataGraph(int count, bool addEdges = true, int edgeCountMult = 25) { var graph = new GraphExample(); foreach (var item in DataSource.Take(count)) - graph.AddVertex(new DataVertex(item.Text) { ID = item.ID, ImageId = Rand.Next(0,3)}); + graph.AddVertex(new DataVertex(item.Text) { ID = item.ID, ImageId = Rand.Next(0, 3) }); var vlist = graph.Vertices.ToList(); var edgeId = count + 1; @@ -76,12 +70,15 @@ public static GraphExample GenerateDataGraph(int count, bool addEdges = true, in { if (Rand.Next(0, 50) > edgeCountMult) continue; var vertex2 = vlist[Rand.Next(0, graph.VertexCount - 1)]; - var txt = string.Format("{0} -> {1}", item.Text, vertex2.Text); - graph.AddEdge(new DataEdge(item, vertex2, Rand.Next(1, 50)) { ID = edgeId, Text = txt, ToolTipText = txt }); + var txt = $"{item.Text} -> {vertex2.Text}"; + graph.AddEdge(new DataEdge(item, vertex2, Rand.Next(1, 50)) + { ID = edgeId, Text = txt, ToolTipText = txt }); edgeId++; } + return graph; } + #endregion public static GraphExample GenerateSugiDataGraph() @@ -115,9 +112,8 @@ public static GraphExample GenerateSugiDataGraph() private static void AddNewEdge(this GraphExample graph, DataVertex source, DataVertex target, long id) { - var text = string.Format("{0} -> {1}", source.Text, target.Text); + var text = $"{source.Text} -> {target.Text}"; graph.AddEdge(new DataEdge(source, target, Rand.Next(1, 50)) { ID = id, Text = text, ToolTipText = text }); - } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Models/SimpleCommand.cs b/Examples/ShowcaseApp.WPF/Models/SimpleCommand.cs index 469ffec..3e4886d 100644 --- a/Examples/ShowcaseApp.WPF/Models/SimpleCommand.cs +++ b/Examples/ShowcaseApp.WPF/Models/SimpleCommand.cs @@ -3,16 +3,10 @@ namespace ShowcaseApp.WPF.Models { - public class SimpleCommand : ICommand - { - public Predicate CanExecuteDelegate { get; set; } - public Action ExecuteDelegate { get; set; } - - public SimpleCommand(Predicate can, Action ex) - { - CanExecuteDelegate = can; - ExecuteDelegate = ex; - } + public class SimpleCommand(Predicate can, Action ex) : ICommand + { + public Predicate CanExecuteDelegate { get; set; } = can; + public Action ExecuteDelegate { get; set; } = ex; #region ICommand Members @@ -25,14 +19,13 @@ public bool CanExecute(object parameter) public event EventHandler CanExecuteChanged { - add { CommandManager.RequerySuggested += value; } - remove { CommandManager.RequerySuggested -= value; } + add => CommandManager.RequerySuggested += value; + remove => CommandManager.RequerySuggested -= value; } public void Execute(object parameter) { - if (ExecuteDelegate != null) - ExecuteDelegate(parameter); + ExecuteDelegate?.Invoke(parameter); } #endregion diff --git a/Examples/ShowcaseApp.WPF/Models/ThemedDataStorage.cs b/Examples/ShowcaseApp.WPF/Models/ThemedDataStorage.cs index 645259d..55475af 100644 --- a/Examples/ShowcaseApp.WPF/Models/ThemedDataStorage.cs +++ b/Examples/ShowcaseApp.WPF/Models/ThemedDataStorage.cs @@ -6,14 +6,14 @@ namespace ShowcaseApp.WPF.Models { public static class ThemedDataStorage { - public static readonly List Gender = new List() - { + public static readonly List Gender = + [ @"Female", - @"Male", - }; + @"Male" + ]; - public static readonly List Professions = new List() - { + public static readonly List Professions = + [ "Expeditor", "Support", "Analyst", @@ -30,10 +30,10 @@ public static class ThemedDataStorage "Project Lead", "Finance Manager", "Executive Director" - }; + ]; - public static readonly List Names = new List() - { + public static readonly List Names = + [ "Madeline Haggerty", "Eldon Deaver", "Latoria Flynn", @@ -133,11 +133,11 @@ public static class ThemedDataStorage "Deandrea Purinton", "Kacy Macek", "Lona Engler", - "Oren Kesten", - }; + "Oren Kesten" + ]; - public static readonly List Images = new List(); - public static readonly List EditorImages = new List(); + public static readonly List Images = []; + public static readonly List EditorImages = []; static ThemedDataStorage() { diff --git a/Examples/ShowcaseApp.WPF/Models/ValueToImageConverter.cs b/Examples/ShowcaseApp.WPF/Models/ValueToImageConverter.cs index 5125528..f0c4d89 100644 --- a/Examples/ShowcaseApp.WPF/Models/ValueToImageConverter.cs +++ b/Examples/ShowcaseApp.WPF/Models/ValueToImageConverter.cs @@ -2,9 +2,8 @@ using System.Globalization; using System.Windows.Data; using System.Windows.Media; -using ShowcaseApp.WPF.Models; -namespace ShowcaseApp.WPF +namespace ShowcaseApp.WPF.Models { public sealed class ValueToImageConverter : IValueConverter diff --git a/Examples/ShowcaseApp.WPF/Pages/Debug/DebugGraph.xaml b/Examples/ShowcaseApp.WPF/Pages/Debug/DebugGraph.xaml index 5c55544..b5c767d 100644 --- a/Examples/ShowcaseApp.WPF/Pages/Debug/DebugGraph.xaml +++ b/Examples/ShowcaseApp.WPF/Pages/Debug/DebugGraph.xaml @@ -5,7 +5,6 @@ xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:wpf="clr-namespace:ShowcaseApp.WPF" xmlns:controls1="https://westermo.com/graphx/" - xmlns:xcad="http://schemas.xceed.com/wpf/xaml/avalondock" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> diff --git a/Examples/ShowcaseApp.WPF/Pages/Debug/DebugGraph.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/Debug/DebugGraph.xaml.cs index 2ca782d..3223e37 100644 --- a/Examples/ShowcaseApp.WPF/Pages/Debug/DebugGraph.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/Debug/DebugGraph.xaml.cs @@ -25,10 +25,19 @@ namespace ShowcaseApp.WPF.Pages /// /// Interaction logic for DebugGraph.xaml /// - public partial class DebugGraph : UserControl, INotifyPropertyChanged + public partial class DebugGraph : INotifyPropertyChanged { private DebugModeEnum _debugMode; - public DebugModeEnum DebugMode { get { return _debugMode; } set { _debugMode = value; OnPropertyChanged("DebugMode"); } } + + public DebugModeEnum DebugMode + { + get => _debugMode; + set + { + _debugMode = value; + OnPropertyChanged("DebugMode"); + } + } public DebugGraph() { @@ -40,47 +49,49 @@ public DebugGraph() butVCP.Click += butVCP_Click; butEdgeLabels.Click += butEdgeLabels_Click; butGroupedGraph.Click += butGroupedGraph_Click; - cbDebugMode.ItemsSource = Enum.GetValues(typeof(DebugModeEnum)).Cast(); + cbDebugMode.ItemsSource = Enum.GetValues().Cast(); cbDebugMode.SelectionChanged += cbDebugMode_SelectionChanged; dg_zoomctrl.PropertyChanged += dg_zoomctrl_PropertyChanged; CreateNewArea(); dg_zoomctrl.ZoomStep = 100; } - void butGroupedGraph_Click(object sender, RoutedEventArgs e) + private void butGroupedGraph_Click(object sender, RoutedEventArgs e) { CreateNewArea(); - dg_Area.LogicCore.Graph = ShowcaseHelper.GenerateDataGraph(10, true); + if (dg_Area.LogicCore is null) return; + dg_Area.LogicCore.Graph = ShowcaseHelper.GenerateDataGraph(10); dg_Area.LogicCore.Graph.Vertices.Take(5).ForEach(a => a.GroupId = 1); - dg_Area.LogicCore.Graph.Vertices.Where(a=> a.GroupId == 0).ForEach(a => a.GroupId = 2); + dg_Area.LogicCore.Graph.Vertices.Where(a => a.GroupId == 0).ForEach(a => a.GroupId = 2); dg_Area.LogicCore.DefaultOverlapRemovalAlgorithm = OverlapRemovalAlgorithmTypeEnum.None; //generate group params var prms = new List> { - new AlgorithmGroupParameters + new() { GroupId = 1, LayoutAlgorithm = new RandomLayoutAlgorithm( - new RandomLayoutAlgorithmParams {Bounds = new Rect(0, 0, 500, 500)}), - - // ZoneRectangle = new Rect(0, 0, 500, 500) + new RandomLayoutAlgorithmParams { Bounds = new Rect(0, 0, 500, 500) }), + + // ZoneRectangle = new Rect(0, 0, 500, 500) }, - new AlgorithmGroupParameters + new() { GroupId = 2, LayoutAlgorithm = new RandomLayoutAlgorithm( - new RandomLayoutAlgorithmParams {Bounds = new Rect(0, 0, 500, 500)}), + new RandomLayoutAlgorithmParams { Bounds = new Rect(0, 0, 500, 500) }), - // ZoneRectangle = new Rect(1000, 0, 500, 500) + // ZoneRectangle = new Rect(1000, 0, 500, 500) } }; var gParams = new GroupingLayoutAlgorithmParameters(prms, true); //generate grouping algo dg_Area.LogicCore.ExternalLayoutAlgorithm = - new GroupingLayoutAlgorithm>(dg_Area.LogicCore.Graph, null, gParams); + new GroupingLayoutAlgorithm>( + dg_Area.LogicCore.Graph, null, gParams); //generate graphs dg_Area.GenerateGraph(); @@ -100,85 +111,88 @@ void butGroupedGraph_Click(object sender, RoutedEventArgs e) GraphAreaBase.SetX(rect, item.ZoneRectangle.Value.X); GraphAreaBase.SetY(rect, item.ZoneRectangle.Value.Y); } + dg_zoomctrl.ZoomToFill(); } - void dg_zoomctrl_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void dg_zoomctrl_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Zoom") { - Debug.WriteLine("Zoom: "+ dg_zoomctrl.Zoom); + Debug.WriteLine("Zoom: " + dg_zoomctrl.Zoom); } } - void CreateNewArea() + private void CreateNewArea() { if (dg_Area != null) { dg_Area.GenerateGraphFinished -= dg_Area_GenerateGraphFinished; dg_Area.RelayoutFinished -= dg_Area_GenerateGraphFinished; + dg_Area.ClearLayout(); + dg_Area.Dispose(); } - dg_Area.ClearLayout(); - dg_Area.Dispose(); + dg_Area = new GraphAreaExample { Name = "dg_Area", LogicCore = new LogicCoreExample(), - Resources = new ResourceDictionary {Source = new Uri("/Templates/Debug/TestTemplates.xaml", UriKind.RelativeOrAbsolute)} + Resources = new ResourceDictionary + { Source = new Uri("/Templates/Debug/TestTemplates.xaml", UriKind.RelativeOrAbsolute) } }; dg_Area.SetVerticesDrag(true, true); dg_zoomctrl.Content = dg_Area; dg_Area.ShowAllEdgesLabels(false); - } - void dg_Area_GenerateGraphFinished(object sender, EventArgs e) + private void dg_Area_GenerateGraphFinished(object sender, EventArgs e) { dg_zoomctrl.ZoomToFill(); } - void butEdgeLabels_Click(object sender, RoutedEventArgs e) + private void butEdgeLabels_Click(object sender, RoutedEventArgs e) { CreateNewArea(); - dg_Area.ShowAllEdgesLabels(true); - dg_Area.AlignAllEdgesLabels(true); - dg_Area.ShowAllEdgesArrows(true); - + dg_Area.ShowAllEdgesLabels(); + dg_Area.AlignAllEdgesLabels(); + dg_Area.ShowAllEdgesArrows(); + if (dg_Area.LogicCore is null) return; dg_Area.LogicCore.Graph = ShowcaseHelper.GenerateDataGraph(2, false); - var vlist = dg_Area.LogicCore.Graph.Vertices.ToList(); - var edge = new DataEdge(vlist[0], vlist[1]) {Text = "Testing edge labels..."}; + var vertexList = dg_Area.LogicCore.Graph.Vertices.ToList(); + var edge = new DataEdge(vertexList[0], vertexList[1]) { Text = "Testing edge labels..." }; dg_Area.LogicCore.Graph.AddEdge(edge); - dg_Area.PreloadGraph(new Dictionary { {vlist[0], new Point()}, {vlist[1], new Point(0, 200)}}); + dg_Area.PreloadGraph(new Dictionary + { { vertexList[0], new Point() }, { vertexList[1], new Point(0, 200) } }); dg_Area.VertexList.Values.ToList().ForEach(a => a.SetConnectionPointsVisibility(false)); } - void butVCP_Click(object sender, RoutedEventArgs e) + private void butVCP_Click(object sender, RoutedEventArgs e) { CreateNewArea(); - dg_Area.VertexList.Values.ToList().ForEach(a=> a.SetConnectionPointsVisibility(true)); - dg_Area.LogicCore.Graph = ShowcaseHelper.GenerateDataGraph(6, false); + dg_Area.VertexList.Values.ToList().ForEach(a => a.SetConnectionPointsVisibility(true)); + dg_Area.LogicCore!.Graph = ShowcaseHelper.GenerateDataGraph(6, false); var vlist = dg_Area.LogicCore.Graph.Vertices.ToList(); var edge = new DataEdge(vlist[0], vlist[1]) { SourceConnectionPointId = 1, TargetConnectionPointId = 1 }; dg_Area.LogicCore.Graph.AddEdge(edge); edge = new DataEdge(vlist[0], vlist[0]) { SourceConnectionPointId = 1, TargetConnectionPointId = 1 }; dg_Area.LogicCore.Graph.AddEdge(edge); - - + dg_Area.LogicCore.DefaultLayoutAlgorithm = LayoutAlgorithmTypeEnum.ISOM; dg_Area.LogicCore.DefaultOverlapRemovalAlgorithm = OverlapRemovalAlgorithmTypeEnum.FSA; - dg_Area.LogicCore.DefaultOverlapRemovalAlgorithmParams = dg_Area.LogicCore.AlgorithmFactory.CreateOverlapRemovalParameters(OverlapRemovalAlgorithmTypeEnum.FSA); + dg_Area.LogicCore.DefaultOverlapRemovalAlgorithmParams = + dg_Area.LogicCore.AlgorithmFactory.CreateOverlapRemovalParameters(OverlapRemovalAlgorithmTypeEnum.FSA); ((OverlapRemovalParameters)dg_Area.LogicCore.DefaultOverlapRemovalAlgorithmParams).HorizontalGap = 50; ((OverlapRemovalParameters)dg_Area.LogicCore.DefaultOverlapRemovalAlgorithmParams).VerticalGap = 50; dg_Area.LogicCore.DefaultEdgeRoutingAlgorithm = EdgeRoutingAlgorithmTypeEnum.None; - dg_Area.GenerateGraph(true); + dg_Area.GenerateGraph(); var vertex = dg_Area.VertexList[edge.Target]; - - var newVcp = new StaticVertexConnectionPoint {Id = 5, Margin = new Thickness(2,0,0,0)}; + + var newVcp = new StaticVertexConnectionPoint { Id = 5, Margin = new Thickness(2, 0, 0, 0) }; var cc = new Border { Margin = new Thickness(2, 0, 0, 0), @@ -186,46 +200,46 @@ void butVCP_Click(object sender, RoutedEventArgs e) Child = newVcp }; edge.TargetConnectionPointId = 5; - vertex.VCPRoot.Children.Add(cc); + vertex.VCPRoot?.Children.Add(cc); vertex.VertexConnectionPointsList.Add(newVcp); dg_Area.EdgesList[edge].UpdateEdge(); dg_Area.UpdateAllEdges(true); } - void butRelayout_Click(object sender, RoutedEventArgs e) + private void butRelayout_Click(object sender, RoutedEventArgs e) { - dg_Area.RelayoutGraph(true); + dg_Area.RelayoutGraph(true); } - void butGeneral_Click(object sender, RoutedEventArgs e) + private void butGeneral_Click(object sender, RoutedEventArgs e) { CreateNewArea(); - dg_Area.LogicCore.Graph = ShowcaseHelper.GenerateDataGraph(2, false); + dg_Area.LogicCore!.Graph = ShowcaseHelper.GenerateDataGraph(2, false); dg_Area.LogicCore.Graph.Vertices.First().IsBlue = true; - var vlist = dg_Area.LogicCore.Graph.Vertices.ToList(); //dg_Area.LogicCore.Graph.AddEdge(new DataEdge(vlist[0], vlist[1]) { ArrowTarget = true}); //dg_Area.LogicCore.Graph.AddEdge(new DataEdge(vlist[0], vlist[2]) { ArrowTarget = true }); //dg_Area.LogicCore.Graph.AddEdge(new DataEdge(vlist[0], vlist[3]) { ArrowTarget = true }); //dg_Area.LogicCore.Graph.AddEdge(new DataEdge(vlist[0], vlist[4]) { ArrowTarget = true }); - - + + dg_Area.LogicCore.EdgeCurvingEnabled = true; dg_Area.LogicCore.DefaultLayoutAlgorithm = LayoutAlgorithmTypeEnum.EfficientSugiyama; dg_Area.SetVerticesMathShape(VertexShape.Ellipse); - dg_Area.GenerateGraph(true); - + dg_Area.GenerateGraph(); + dg_Area.VertexList.Values.ToList().ForEach(a => a.SetConnectionPointsVisibility(false)); } - void butEdgePointer_Click(object sender, RoutedEventArgs e) + private void butEdgePointer_Click(object sender, RoutedEventArgs e) { CreateNewArea(); dg_Area.VertexList.Values.ToList().ForEach(a => a.SetConnectionPointsVisibility(false)); } #region DebugMode switches - void cbDebugMode_SelectionChanged(object sender, SelectionChangedEventArgs e) + + private void cbDebugMode_SelectionChanged(object sender, SelectionChangedEventArgs e) { switch (DebugMode) { @@ -237,7 +251,8 @@ void cbDebugMode_SelectionChanged(object sender, SelectionChangedEventArgs e) case DebugModeEnum.Animations: CleanDMERCurving(); CleanDMER(); - dg_Area.MoveAnimation = AnimationFactory.CreateMoveAnimation(MoveAnimation.Move, TimeSpan.FromSeconds(0.5)); + dg_Area.MoveAnimation = + AnimationFactory.CreateMoveAnimation(MoveAnimation.Move, TimeSpan.FromSeconds(0.5)); dg_Area.MoveAnimation.Completed += dg_Area_GenerateGraphFinished; dg_Area.MouseOverAnimation = AnimationFactory.CreateMouseOverAnimation(MouseOverAnimation.Scale); dg_Area.DeleteAnimation = AnimationFactory.CreateDeleteAnimation(DeleteAnimation.Fade); @@ -275,7 +290,7 @@ private void CleanDMAnimations() dg_Area.MouseOverAnimation = null; dg_Area.DeleteAnimation = null; } - + #endregion #region INotifyPropertyChanged @@ -285,8 +300,9 @@ private void CleanDMAnimations() protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; - if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } + #endregion } @@ -297,4 +313,4 @@ public enum DebugModeEnum EdgeRoutingEnabled, EdgeRoutingWithCurvingEnabled } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/DynamicGraph.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/DynamicGraph.xaml.cs index bdd2fb6..263d2c8 100644 --- a/Examples/ShowcaseApp.WPF/Pages/DynamicGraph.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/DynamicGraph.xaml.cs @@ -1,10 +1,8 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; -using System.Windows.Media; using Westermo.GraphX; using Westermo.GraphX.Common.Enums; using Westermo.GraphX.Controls; @@ -40,7 +38,7 @@ public DynamicGraph() dgLogic.EdgeCurvingEnabled = true; dgLogic.Graph = new GraphExample(); dg_Area.MoveAnimation = AnimationFactory.CreateMoveAnimation(MoveAnimation.Move, TimeSpan.FromSeconds(0.5)); - dg_Area.MoveAnimation.Completed += MoveAnimation_Completed; + dg_Area.MoveAnimation!.Completed += MoveAnimation_Completed; dg_Area.VertexSelected += dg_Area_VertexSelected; dg_test.Visibility = Visibility.Collapsed; dg_zoomctrl.AreaSelected += dg_zoomctrl_AreaSelected; @@ -51,18 +49,18 @@ public DynamicGraph() dg_zoomctrl.DragEnter += dg_Area_DragEnter; dg_zoomctrl.IsAnimationEnabled = false; - /* dg_Area.VertexSelected += dg_Area_VertexSelectedForED; - dg_zoomctrl.PreviewMouseMove += dg_Area_MouseMove; - dg_zoomctrl.MouseDown += dg_zoomctrl_MouseDown;*/ + /* dg_Area.VertexSelected += dg_Area_VertexSelectedForED; + dg_zoomctrl.PreviewMouseMove += dg_Area_MouseMove; + dg_zoomctrl.MouseDown += dg_zoomctrl_MouseDown;*/ dg_Area.SetVerticesDrag(true, true); Loaded += DynamicGraph_Loaded; Unloaded += DynamicGraph_Unloaded; } - private bool loaded = false; - private Predicate _originalGlobalIsSnapping = null; - private Predicate _originalGlobalIsSnappingIndividually = null; + private bool loaded; + private Predicate _originalGlobalIsSnapping; + private Predicate _originalGlobalIsSnappingIndividually; private void DynamicGraph_Loaded(object sender, RoutedEventArgs e) { @@ -85,126 +83,127 @@ private void DynamicGraph_Unloaded(object sender, RoutedEventArgs e) DragBehaviour.GlobalIsIndividualSnappingPredicate = _originalGlobalIsSnappingIndividually; } - void MoveAnimation_Completed(object sender, EventArgs e) + private void MoveAnimation_Completed(object sender, EventArgs e) { dg_zoomctrl.ZoomToFill(); } #region Manual edge drawing - /* private bool _isInEdMode; - private PathGeometry _edGeo; - private VertexControl _edVertex; - private EdgeControl _edEdge; - private DataVertex _edFakeDv; + /* private bool _isInEdMode; + private PathGeometry _edGeo; + private VertexControl _edVertex; + private EdgeControl _edEdge; + private DataVertex _edFakeDv; + + void dg_zoomctrl_MouseDown(object sender, MouseButtonEventArgs e) + { + if (!_isInEdMode || _edGeo == null || _edEdge == null || _edVertex == null || e.LeftButton != MouseButtonState.Pressed) return; + //place point + var pos = dg_zoomctrl.TranslatePoint(e.GetPosition(dg_zoomctrl), dg_Area); + var lastseg = _edGeo.Figures[0].Segments[_edGeo.Figures[0].Segments.Count - 1] as PolyLineSegment; + if (lastseg != null) lastseg.Points.Add(pos); + _edEdge.SetEdgePathManually(_edGeo); + } + + void dg_Area_MouseMove(object sender, MouseEventArgs e) + { + if (!_isInEdMode || _edGeo == null || _edEdge == null || _edVertex == null) return; + var pos = dg_zoomctrl.TranslatePoint(e.GetPosition(dg_zoomctrl), dg_Area); + var lastseg = _edGeo.Figures[0].Segments[_edGeo.Figures[0].Segments.Count - 1] as PolyLineSegment; + if (lastseg != null) lastseg.Points[lastseg.Points.Count - 1] = pos; + _edEdge.SetEdgePathManually(_edGeo); + } + + void dg_Area_VertexSelectedForED(object sender, VertexSelectedEventArgs args) + { + if (!_isInEdMode) return; + if (_edVertex == null) //select starting vertex + { + _edVertex = args.VertexControl; + _edFakeDv = new DataVertex { ID = -666 }; + _edGeo = new PathGeometry(new PathFigureCollection { new PathFigure { IsClosed = false, StartPoint = _edVertex.GetPosition(), Segments = new PathSegmentCollection { new PolyLineSegment(new List { new Point() }, true) } } }); + var dedge = new DataEdge(_edVertex.Vertex as DataVertex, _edFakeDv); + _edEdge = new EdgeControl(_edVertex, null, dedge) { ManualDrawing = true }; + dg_Area.AddEdge(dedge, _edEdge); + dg_Area.LogicCore.Graph.AddVertex(_edFakeDv); + dg_Area.LogicCore.Graph.AddEdge(dedge); + _edEdge.SetEdgePathManually(_edGeo); + } + else if (!Equals(_edVertex, args.VertexControl)) //finish draw + { + _edEdge.Target = args.VertexControl; + var dedge = _edEdge.Edge as DataEdge; + if (dedge != null) dedge.Target = args.VertexControl.Vertex as DataVertex; + var fig = _edGeo.Figures[0]; + var seg = fig.Segments[_edGeo.Figures[0].Segments.Count - 1] as PolyLineSegment; + + if (seg != null && seg.Points.Count > 0) + { + var targetPos = _edEdge.Target.GetPosition(); + var sourcePos = _edEdge.Source.GetPosition(); + //get the size of the source + var sourceSize = new Size + { + Width = _edEdge.Source.ActualWidth, + Height = _edEdge.Source.ActualHeight + }; + var targetSize = new Size + { + Width = _edEdge.Target.ActualWidth, + Height = _edEdge.Target.ActualHeight + }; + + var srcStart = seg.Points.Count == 0 ? fig.StartPoint : seg.Points[0]; + var srcEnd = seg.Points.Count > 1 ? (seg.Points[seg.Points.Count - 1] == targetPos ? seg.Points[seg.Points.Count - 2] : seg.Points[seg.Points.Count - 1]) : fig.StartPoint; + var p1 = GeometryHelper.GetEdgeEndpoint(sourcePos, new Rect(sourceSize), srcStart, _edEdge.Source.VertexShape); + var p2 = GeometryHelper.GetEdgeEndpoint(targetPos, new Rect(targetSize), srcEnd, _edEdge.Target.VertexShape); + + + fig.StartPoint = p1; + if (seg.Points.Count > 1) + seg.Points[seg.Points.Count - 1] = p2; + } + GeometryHelper.TryFreeze(_edGeo); + _edEdge.SetEdgePathManually(new PathGeometry(_edGeo.Figures)); + _isInEdMode = false; + ClearEdgeDrawing(); + } + } + + + void ClearEdgeDrawing() + { + _edGeo = null; + if (_edFakeDv != null) + dg_Area.LogicCore.Graph.RemoveVertex(_edFakeDv); + _edFakeDv = null; + _edVertex = null; + _edEdge = null; + } + + private void dg_butdraw_Click(object sender, RoutedEventArgs e) + { + if (!_isInEdMode) + { + if (dg_Area.VertexList.Count() < 2) + { + MessageBox.Show("Please add more vertices before proceed with this action!", "Starting to draw custom edge...", MessageBoxButton.OK, MessageBoxImage.Information); + return; + } + MessageBox.Show("Please select any vertex to define edge starting point!", "Starting to draw custom edge...", MessageBoxButton.OK, MessageBoxImage.Information); + } + else + { + MessageBox.Show("Edge drawing mode has been canceled!"); + if (_edEdge != null) + _edEdge.SetEdgePathManually(null); + ClearEdgeDrawing(); + } + _isInEdMode = !_isInEdMode; + } + */ - void dg_zoomctrl_MouseDown(object sender, MouseButtonEventArgs e) - { - if (!_isInEdMode || _edGeo == null || _edEdge == null || _edVertex == null || e.LeftButton != MouseButtonState.Pressed) return; - //place point - var pos = dg_zoomctrl.TranslatePoint(e.GetPosition(dg_zoomctrl), dg_Area); - var lastseg = _edGeo.Figures[0].Segments[_edGeo.Figures[0].Segments.Count - 1] as PolyLineSegment; - if (lastseg != null) lastseg.Points.Add(pos); - _edEdge.SetEdgePathManually(_edGeo); - } - - void dg_Area_MouseMove(object sender, MouseEventArgs e) - { - if (!_isInEdMode || _edGeo == null || _edEdge == null || _edVertex == null) return; - var pos = dg_zoomctrl.TranslatePoint(e.GetPosition(dg_zoomctrl), dg_Area); - var lastseg = _edGeo.Figures[0].Segments[_edGeo.Figures[0].Segments.Count - 1] as PolyLineSegment; - if (lastseg != null) lastseg.Points[lastseg.Points.Count - 1] = pos; - _edEdge.SetEdgePathManually(_edGeo); - } - - void dg_Area_VertexSelectedForED(object sender, VertexSelectedEventArgs args) - { - if (!_isInEdMode) return; - if (_edVertex == null) //select starting vertex - { - _edVertex = args.VertexControl; - _edFakeDv = new DataVertex { ID = -666 }; - _edGeo = new PathGeometry(new PathFigureCollection { new PathFigure { IsClosed = false, StartPoint = _edVertex.GetPosition(), Segments = new PathSegmentCollection { new PolyLineSegment(new List { new Point() }, true) } } }); - var dedge = new DataEdge(_edVertex.Vertex as DataVertex, _edFakeDv); - _edEdge = new EdgeControl(_edVertex, null, dedge) { ManualDrawing = true }; - dg_Area.AddEdge(dedge, _edEdge); - dg_Area.LogicCore.Graph.AddVertex(_edFakeDv); - dg_Area.LogicCore.Graph.AddEdge(dedge); - _edEdge.SetEdgePathManually(_edGeo); - } - else if (!Equals(_edVertex, args.VertexControl)) //finish draw - { - _edEdge.Target = args.VertexControl; - var dedge = _edEdge.Edge as DataEdge; - if (dedge != null) dedge.Target = args.VertexControl.Vertex as DataVertex; - var fig = _edGeo.Figures[0]; - var seg = fig.Segments[_edGeo.Figures[0].Segments.Count - 1] as PolyLineSegment; - - if (seg != null && seg.Points.Count > 0) - { - var targetPos = _edEdge.Target.GetPosition(); - var sourcePos = _edEdge.Source.GetPosition(); - //get the size of the source - var sourceSize = new Size - { - Width = _edEdge.Source.ActualWidth, - Height = _edEdge.Source.ActualHeight - }; - var targetSize = new Size - { - Width = _edEdge.Target.ActualWidth, - Height = _edEdge.Target.ActualHeight - }; - - var srcStart = seg.Points.Count == 0 ? fig.StartPoint : seg.Points[0]; - var srcEnd = seg.Points.Count > 1 ? (seg.Points[seg.Points.Count - 1] == targetPos ? seg.Points[seg.Points.Count - 2] : seg.Points[seg.Points.Count - 1]) : fig.StartPoint; - var p1 = GeometryHelper.GetEdgeEndpoint(sourcePos, new Rect(sourceSize), srcStart, _edEdge.Source.VertexShape); - var p2 = GeometryHelper.GetEdgeEndpoint(targetPos, new Rect(targetSize), srcEnd, _edEdge.Target.VertexShape); - - - fig.StartPoint = p1; - if (seg.Points.Count > 1) - seg.Points[seg.Points.Count - 1] = p2; - } - GeometryHelper.TryFreeze(_edGeo); - _edEdge.SetEdgePathManually(new PathGeometry(_edGeo.Figures)); - _isInEdMode = false; - ClearEdgeDrawing(); - } - } - - - void ClearEdgeDrawing() - { - _edGeo = null; - if (_edFakeDv != null) - dg_Area.LogicCore.Graph.RemoveVertex(_edFakeDv); - _edFakeDv = null; - _edVertex = null; - _edEdge = null; - } - - private void dg_butdraw_Click(object sender, RoutedEventArgs e) - { - if (!_isInEdMode) - { - if (dg_Area.VertexList.Count() < 2) - { - MessageBox.Show("Please add more vertices before proceed with this action!", "Starting to draw custom edge...", MessageBoxButton.OK, MessageBoxImage.Information); - return; - } - MessageBox.Show("Please select any vertex to define edge starting point!", "Starting to draw custom edge...", MessageBoxButton.OK, MessageBoxImage.Information); - } - else - { - MessageBox.Show("Edge drawing mode has been canceled!"); - if (_edEdge != null) - _edEdge.SetEdgePathManually(null); - ClearEdgeDrawing(); - } - _isInEdMode = !_isInEdMode; - } - */ #endregion private void dg_findrandom_Click(object sender, RoutedEventArgs e) @@ -216,25 +215,32 @@ private void dg_findrandom_Click(object sender, RoutedEventArgs e) const int offset = 100; var pos = vc.GetPosition(); - dg_zoomctrl.ZoomToContent(new Rect(pos.X - offset, pos.Y - offset, vc.ActualWidth + offset * 2, vc.ActualHeight + offset * 3)); + dg_zoomctrl.ZoomToContent(new Rect(pos.X - offset, pos.Y - offset, vc.ActualWidth + offset * 2, + vc.ActualHeight + offset * 3)); } - void dg_zoomctrl_AreaSelected(object sender, AreaSelectedEventArgs args) + private void dg_zoomctrl_AreaSelected(object sender, AreaSelectedEventArgs args) { var r = args.Rectangle; - foreach (var item in from item in dg_Area.VertexList let offset = item.Value.GetPosition() let irect = new Rect(offset.X, offset.Y, item.Value.ActualWidth, item.Value.ActualHeight) where irect.IntersectsWith(r) select item) { + foreach (var item in from item in dg_Area.VertexList + let offset = item.Value.GetPosition() + let irect = new Rect(offset.X, offset.Y, item.Value.ActualWidth, item.Value.ActualHeight) + where irect.IntersectsWith(r) + select item) + { SelectVertex(item.Value); } } #region Dragging example - void dg_dragsource_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + + private void dg_dragsource_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var data = new DataObject(typeof(object), new object()); DragDrop.DoDragDrop(dg_dragsource, data, DragDropEffects.Link); } - static void dg_Area_DragEnter(object sender, DragEventArgs e) + private static void dg_Area_DragEnter(object sender, DragEventArgs e) { //don't show drag effect if we are on drag source or don't have any item of needed type dragged if (!e.Data.GetDataPresent(typeof(object)) || sender == e.Source) @@ -243,9 +249,9 @@ static void dg_Area_DragEnter(object sender, DragEventArgs e) } } - void dg_Area_Drop(object sender, DragEventArgs e) + private void dg_Area_Drop(object sender, DragEventArgs e) { - if (!e.Data.GetDataPresent(typeof (object))) return; + if (!e.Data.GetDataPresent(typeof(object))) return; //how to get dragged data by its type var pos = dg_zoomctrl.TranslatePoint(e.GetPosition(dg_zoomctrl), dg_Area); var data = ThemedDataStorage.FillDataVertex(new DataVertex()); @@ -256,9 +262,9 @@ void dg_Area_Drop(object sender, DragEventArgs e) #endregion - void dg_Area_VertexSelected(object sender, VertexSelectedEventArgs args) + private void dg_Area_VertexSelected(object sender, VertexSelectedEventArgs args) { - if (args.MouseArgs.LeftButton == MouseButtonState.Pressed) + if (args.MouseArgs!.LeftButton == MouseButtonState.Pressed) { if (Keyboard.IsKeyDown(Key.LeftCtrl)) SelectVertex(args.VertexControl); @@ -268,42 +274,46 @@ void dg_Area_VertexSelected(object sender, VertexSelectedEventArgs args) var countTagged = dg_Area.VertexList.Values.Count(DragBehaviour.GetIsTagged); var isTagged = DragBehaviour.GetIsTagged(args.VertexControl); args.VertexControl.ContextMenu = new ContextMenu(); - var mi = new MenuItem { Header = "Delete item" + (isTagged && countTagged > 1 ? "s" : ""), Tag = args.VertexControl, Margin = new Thickness(5) }; + var mi = new MenuItem + { + Header = "Delete item" + (isTagged && countTagged > 1 ? "s" : ""), Tag = args.VertexControl, + Margin = new Thickness(5) + }; mi.Click += mi_Click; args.VertexControl.ContextMenu.Items.Add(mi); args.VertexControl.ContextMenu.IsOpen = true; } } - void mi_Click(object sender, RoutedEventArgs e) + private void mi_Click(object sender, RoutedEventArgs e) { - var menuItem = sender as MenuItem; - if (menuItem == null) return; - var vc = menuItem.Tag as VertexControl; + if (sender is not MenuItem menuItem) return; + if (menuItem.Tag is not VertexControl vc) return; //if clicked vertex is tagged then remove all tagged vertices if (DragBehaviour.GetIsTagged(vc)) dg_remvertex_Click(null, null); else //else remove only selected vertex - if (vc != null) SafeRemoveVertex(vc); + SafeRemoveVertex(vc); } - void dg_remedge_Click(object sender, RoutedEventArgs e) + private void dg_remedge_Click(object sender, RoutedEventArgs e) { if (!dg_Area.EdgesList.Any()) return; //remove visual and data edge dg_Area.RemoveEdge(dg_Area.EdgesList.Last().Key, true); } - void dg_addedge_Click(object sender, RoutedEventArgs e) + private void dg_addedge_Click(object sender, RoutedEventArgs e) { //add new edge between random vertices var dataEdge = GenerateRandomEdge(); if (dataEdge == null) return; - var ec = new EdgeControl(dg_Area.VertexList.FirstOrDefault(a => a.Key == dataEdge.Source).Value, dg_Area.VertexList.FirstOrDefault(a => a.Key == dataEdge.Target).Value, dataEdge); + var ec = new EdgeControl(dg_Area.VertexList.FirstOrDefault(a => a.Key == dataEdge.Source).Value, + dg_Area.VertexList.FirstOrDefault(a => a.Key == dataEdge.Target).Value, dataEdge); dg_Area.InsertEdgeAndData(dataEdge, ec); } - void dg_remvertex_Click(object sender, RoutedEventArgs e) + private void dg_remvertex_Click(object sender, RoutedEventArgs e) { //remove all tagged vertices from the graph entirely dg_Area.VertexList.Values @@ -312,7 +322,7 @@ void dg_remvertex_Click(object sender, RoutedEventArgs e) .ForEach(SafeRemoveVertex); } - void dg_addvertex_Click(object sender, RoutedEventArgs e) + private void dg_addvertex_Click(object sender, RoutedEventArgs e) { var data = ThemedDataStorage.FillDataVertex(new DataVertex()); dg_Area.AddVertexAndData(data, new VertexControl(data)); @@ -323,7 +333,9 @@ void dg_addvertex_Click(object sender, RoutedEventArgs e) { dg_Area.VertexList.First().Value.SetPosition(0, 0); dg_Area.UpdateLayout(); //update layout to update vertex size - } else dg_Area.RelayoutGraph(true); + } + else dg_Area.RelayoutGraph(true); + dg_zoomctrl.ZoomToFill(); } @@ -333,7 +345,8 @@ void dg_addvertex_Click(object sender, RoutedEventArgs e) /// vertexControl object private void SafeRemoveVertex(VertexControl vc) { - dg_Area.RemoveVertexAndEdges(vc.Vertex as DataVertex); + if (vc.Vertex is not DataVertex vertex) return; + dg_Area.RemoveVertexAndEdges(vertex); dg_zoomctrl.ZoomToFill(); } @@ -343,7 +356,7 @@ private void SafeRemoveVertex(VertexControl vc) private DataEdge GenerateRandomEdge() { if (dg_Area.VertexList.Count < 2) return null; - var vlist = dg_Area.LogicCore.Graph.Vertices.ToList(); + var vlist = dg_Area.LogicCore!.Graph.Vertices.ToList(); var rnd1 = vlist[ShowcaseHelper.Rand.Next(0, vlist.Count - 1)]; vlist.Remove(rnd1); var rnd2 = vlist[ShowcaseHelper.Rand.Next(0, vlist.Count - 1)]; @@ -386,8 +399,9 @@ private double ExaggeratedSnappingXModifier(GraphAreaBase area, DependencyObject { if (dg_snapExaggerate.IsChecked ?? false) { - return System.Math.Round(val * 0.01) * 100.0; + return Math.Round(val * 0.01) * 100.0; } + return DragBehaviour.GlobalXSnapModifier(area, obj, val); } @@ -395,9 +409,10 @@ private double ExaggeratedSnappingYModifier(GraphAreaBase area, DependencyObject { if (dg_snapExaggerate.IsChecked ?? false) { - return System.Math.Round(val * 0.01) * 100.0; + return Math.Round(val * 0.01) * 100.0; } + return DragBehaviour.GlobalYSnapModifier(area, obj, val); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/EdgeRoutingGraph.xaml b/Examples/ShowcaseApp.WPF/Pages/EdgeRoutingGraph.xaml index 5df928c..2391cb9 100644 --- a/Examples/ShowcaseApp.WPF/Pages/EdgeRoutingGraph.xaml +++ b/Examples/ShowcaseApp.WPF/Pages/EdgeRoutingGraph.xaml @@ -27,7 +27,7 @@ - + diff --git a/Examples/ShowcaseApp.WPF/Pages/EdgeRoutingGraph.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/EdgeRoutingGraph.xaml.cs index 6a46647..529f928 100644 --- a/Examples/ShowcaseApp.WPF/Pages/EdgeRoutingGraph.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/EdgeRoutingGraph.xaml.cs @@ -1,11 +1,9 @@ using System; -using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; -using Westermo.GraphX; using Westermo.GraphX.Common.Enums; using Westermo.GraphX.Logic.Algorithms.EdgeRouting; using Westermo.GraphX.Controls; @@ -19,14 +17,43 @@ namespace ShowcaseApp.WPF.Pages /// /// Interaction logic for EdgeRoutingGraph.xaml /// - public partial class EdgeRoutingGraph : UserControl, INotifyPropertyChanged + public partial class EdgeRoutingGraph : INotifyPropertyChanged { private PathFinderEdgeRoutingParameters _pfPrms; - public PathFinderEdgeRoutingParameters PfErParameters { get { return _pfPrms; } set { _pfPrms = value; OnPropertyChanged("PfErParameters"); } } + + public PathFinderEdgeRoutingParameters PfErParameters + { + get => _pfPrms; + set + { + _pfPrms = value; + OnPropertyChanged("PfErParameters"); + } + } + private SimpleERParameters _simplePrms; - public SimpleERParameters SimpleErParameters { get { return _simplePrms; } set { _simplePrms = value; OnPropertyChanged("SimpleErParameters"); } } + + public SimpleERParameters SimpleErParameters + { + get => _simplePrms; + set + { + _simplePrms = value; + OnPropertyChanged("SimpleErParameters"); + } + } + private BundleEdgeRoutingParameters _bundlePrms; - public BundleEdgeRoutingParameters BundleEdgeRoutingParameters { get { return _bundlePrms; } set { _bundlePrms = value; OnPropertyChanged("BundleEdgeRoutingParameters"); } } + + public BundleEdgeRoutingParameters BundleEdgeRoutingParameters + { + get => _bundlePrms; + set + { + _bundlePrms = value; + OnPropertyChanged("BundleEdgeRoutingParameters"); + } + } private readonly LogicCoreExample _logicCore; @@ -40,21 +67,28 @@ public EdgeRoutingGraph() erg_Area.EdgeLabelFactory = new DefaultEdgelabelFactory(); erg_showEdgeArrows.IsChecked = true; - BundleEdgeRoutingParameters = (BundleEdgeRoutingParameters)_logicCore.AlgorithmFactory.CreateEdgeRoutingParameters(EdgeRoutingAlgorithmTypeEnum.Bundling); - SimpleErParameters = (SimpleERParameters)_logicCore.AlgorithmFactory.CreateEdgeRoutingParameters(EdgeRoutingAlgorithmTypeEnum.SimpleER); - PfErParameters = (PathFinderEdgeRoutingParameters)_logicCore.AlgorithmFactory.CreateEdgeRoutingParameters(EdgeRoutingAlgorithmTypeEnum.PathFinder); - - erg_pfprm_formula.ItemsSource = Enum.GetValues(typeof(PathFindAlgorithm)).Cast(); + BundleEdgeRoutingParameters = + (BundleEdgeRoutingParameters)_logicCore.AlgorithmFactory.CreateEdgeRoutingParameters( + EdgeRoutingAlgorithmTypeEnum.Bundling); + SimpleErParameters = + (SimpleERParameters)_logicCore.AlgorithmFactory.CreateEdgeRoutingParameters(EdgeRoutingAlgorithmTypeEnum + .SimpleER); + PfErParameters = + (PathFinderEdgeRoutingParameters)_logicCore.AlgorithmFactory.CreateEdgeRoutingParameters( + EdgeRoutingAlgorithmTypeEnum.PathFinder); + + erg_pfprm_formula.ItemsSource = Enum.GetValues().Cast(); erg_pfprm_formula.SelectedIndex = 0; erg_but_randomgraph.Click += erg_but_randomgraph_Click; erg_but_relayout.Click += erg_but_relayout_Click; erg_useExternalERAlgo.Checked += erg_useExternalERAlgo_Checked; erg_useExternalERAlgo.Unchecked += erg_useExternalERAlgo_Checked; - erg_dashstyle.ItemsSource = Enum.GetValues(typeof(EdgeDashStyle)).Cast(); + erg_dashstyle.ItemsSource = Enum.GetValues().Cast(); erg_dashstyle.SelectedIndex = 0; erg_dashstyle.SelectionChanged += erg_dashstyle_SelectionChanged; - erg_eralgo.ItemsSource = Enum.GetValues(typeof(EdgeRoutingAlgorithmTypeEnum)).Cast(); + erg_eralgo.ItemsSource = Enum.GetValues() + .Cast(); erg_eralgo.SelectedIndex = 0; erg_eralgo.SelectionChanged += erg_eralgo_SelectionChanged; erg_prmsbox.Visibility = Visibility.Collapsed; @@ -77,68 +111,61 @@ public EdgeRoutingGraph() ZoomControl.SetViewFinderVisibility(erg_zoomctrl, Visibility.Visible); } - private void erg_toggleVertex_Click(object sender, RoutedEventArgs e) - { - if (erg_Area.VertexList.First().Value.Visibility == Visibility.Visible) - foreach (var item in erg_Area.VertexList) - item.Value.Visibility = Visibility.Collapsed; - else foreach (var item in erg_Area.VertexList) - item.Value.Visibility = Visibility.Visible; - } - - void erg_enableParallelEdges_Checked(object sender, RoutedEventArgs e) + private void erg_enableParallelEdges_Checked(object sender, RoutedEventArgs e) { - erg_Area.LogicCore.EnableParallelEdges = erg_enableParallelEdges.IsChecked != null && erg_enableParallelEdges.IsChecked.Value; + erg_Area.LogicCore!.EnableParallelEdges = + erg_enableParallelEdges.IsChecked != null && erg_enableParallelEdges.IsChecked.Value; } - void erg_useCurves_Checked(object sender, RoutedEventArgs e) + private void erg_useCurves_Checked(object sender, RoutedEventArgs e) { //update edge curving property - erg_Area.LogicCore.EdgeCurvingEnabled = erg_useCurves.IsChecked != null && erg_useCurves.IsChecked.Value; + erg_Area.LogicCore!.EdgeCurvingEnabled = erg_useCurves.IsChecked != null && erg_useCurves.IsChecked.Value; erg_Area.UpdateAllEdges(); } - void erg_randomizeArrows_Click(object sender, RoutedEventArgs e) + private void erg_randomizeArrows_Click(object sender, RoutedEventArgs e) { foreach (var item in erg_Area.EdgesList.ToList()) - item.Value.SetCurrentValue(EdgeControl.ShowArrowsProperty, Convert.ToBoolean(ShowcaseHelper.Rand.Next(0, 2))); + item.Value.SetCurrentValue(EdgeControlBase.ShowArrowsProperty, + Convert.ToBoolean(ShowcaseHelper.Rand.Next(0, 2))); } - void erg_showEdgeLabels_Checked(object sender, RoutedEventArgs e) + private void erg_showEdgeLabels_Checked(object sender, RoutedEventArgs e) { erg_Area.ShowAllEdgesLabels(erg_showEdgeLabels.IsChecked != null && erg_showEdgeLabels.IsChecked.Value); erg_Area.InvalidateVisual(); } - void erg_alignEdgeLabels_Checked(object sender, RoutedEventArgs e) + private void erg_alignEdgeLabels_Checked(object sender, RoutedEventArgs e) { erg_Area.AlignAllEdgesLabels(erg_alignEdgeLabels.IsChecked != null && erg_alignEdgeLabels.IsChecked.Value); erg_Area.InvalidateVisual(); } - void erg_showEdgeArrows_Checked(object sender, RoutedEventArgs e) + private void erg_showEdgeArrows_Checked(object sender, RoutedEventArgs e) { erg_Area.ShowAllEdgesArrows(erg_showEdgeArrows.IsChecked != null && erg_showEdgeArrows.IsChecked.Value); } - void erg_randomizeAll_Click(object sender, RoutedEventArgs e) + private void erg_randomizeAll_Click(object sender, RoutedEventArgs e) { foreach (var item in erg_Area.EdgesList.ToList()) { - var sarr = Enum.GetValues(typeof(EdgeDashStyle)); - item.Value.DashStyle = (EdgeDashStyle)sarr.GetValue(ShowcaseHelper.Rand.Next(0, sarr.Length - 1)); + var sarr = Enum.GetValues(); + item.Value.DashStyle = (EdgeDashStyle)sarr.GetValue(ShowcaseHelper.Rand.Next(0, sarr.Length - 1))!; } } - void erg_recalculate_Checked(object sender, RoutedEventArgs e) + private void erg_recalculate_Checked(object sender, RoutedEventArgs e) { foreach (var item in erg_Area.GetAllVertexControls()) - DragBehaviour.SetUpdateEdgesOnMove(item, erg_recalculate.IsChecked != null && erg_recalculate.IsChecked.Value); - + DragBehaviour.SetUpdateEdgesOnMove(item, + erg_recalculate.IsChecked != null && erg_recalculate.IsChecked.Value); } - void erg_dashstyle_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void erg_dashstyle_SelectionChanged(object sender, SelectionChangedEventArgs e) { erg_Area.SetEdgesDashStyle((EdgeDashStyle)erg_dashstyle.SelectedItem); } @@ -153,8 +180,7 @@ private void erg_to1_PreviewTextInput(object sender, TextCompositionEventArgs e) e.Handled = CustomHelper.IsDoubleInput(e.Text); if (e.Handled) return; var res = 0.0; - var textBox = sender as TextBox; - if (textBox != null && !double.TryParse(textBox.Text, out res)) return; + if (sender is TextBox textBox && !double.TryParse(textBox.Text, out res)) return; if (res < 0.0 || res > 1.0) e.Handled = false; } @@ -163,13 +189,12 @@ private void erg_tominus1_PreviewTextInput(object sender, TextCompositionEventAr e.Handled = CustomHelper.IsDoubleInput(e.Text); if (e.Handled) return; var res = 0.0; - var textBox = sender as TextBox; - if (textBox != null && !double.TryParse(textBox.Text, out res)) return; + if (sender is TextBox textBox && !double.TryParse(textBox.Text, out res)) return; if (res < -1.0 || res > 0.0) e.Handled = false; } - void erg_eralgo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void erg_eralgo_SelectionChanged(object sender, SelectionChangedEventArgs e) { erg_recalculate.IsEnabled = true; if ((EdgeRoutingAlgorithmTypeEnum)erg_eralgo.SelectedItem == EdgeRoutingAlgorithmTypeEnum.None) @@ -184,12 +209,14 @@ void erg_eralgo_SelectionChanged(object sender, SelectionChangedEventArgs e) bundleer_prms_dp.Visibility = Visibility.Collapsed; pfer_prms_dp.Visibility = Visibility.Collapsed; } + if ((EdgeRoutingAlgorithmTypeEnum)erg_eralgo.SelectedItem == EdgeRoutingAlgorithmTypeEnum.PathFinder) { simpleer_prms_dp.Visibility = Visibility.Collapsed; bundleer_prms_dp.Visibility = Visibility.Collapsed; pfer_prms_dp.Visibility = Visibility.Visible; } + if ((EdgeRoutingAlgorithmTypeEnum)erg_eralgo.SelectedItem == EdgeRoutingAlgorithmTypeEnum.Bundling) { simpleer_prms_dp.Visibility = Visibility.Collapsed; @@ -202,17 +229,21 @@ void erg_eralgo_SelectionChanged(object sender, SelectionChangedEventArgs e) } } - void erg_useExternalERAlgo_Checked(object sender, RoutedEventArgs e) + private void erg_useExternalERAlgo_Checked(object sender, RoutedEventArgs e) { if (erg_useExternalERAlgo.IsChecked == true) { - if (erg_Area.LogicCore.Graph == null) erg_but_randomgraph_Click(null, null); - erg_Area.GetLogicCore().ExternalEdgeRoutingAlgorithm = erg_Area.LogicCore.AlgorithmFactory.CreateEdgeRoutingAlgorithm(EdgeRoutingAlgorithmTypeEnum.SimpleER, new Rect(0, 0, erg_Area.DesiredSize.Width, erg_Area.DesiredSize.Height), erg_Area.LogicCore.Graph, null, null); + if (erg_Area.LogicCore!.Graph == null) erg_but_randomgraph_Click(null, null); + erg_Area.GetLogicCore().ExternalEdgeRoutingAlgorithm = + erg_Area.LogicCore.AlgorithmFactory.CreateEdgeRoutingAlgorithm( + EdgeRoutingAlgorithmTypeEnum.SimpleER, + new Rect(0, 0, erg_Area.DesiredSize.Width, erg_Area.DesiredSize.Height), + erg_Area.LogicCore.Graph, null, null); } else erg_Area.GetLogicCore().ExternalEdgeRoutingAlgorithm = null; } - void erg_but_relayout_Click(object sender, RoutedEventArgs e) + private void erg_but_relayout_Click(object sender, RoutedEventArgs e) { switch ((EdgeRoutingAlgorithmTypeEnum)erg_eralgo.SelectedItem) { @@ -223,56 +254,59 @@ void erg_but_relayout_Click(object sender, RoutedEventArgs e) erg_Area.RelayoutGraph(); break; default: - erg_Area.GenerateGraph(erg_Area.LogicCore.Graph, true); + erg_Area.GenerateGraph(erg_Area.LogicCore!.Graph); break; } } - private Dictionary GenerateRandomVertices(GraphExample graph, int index, int count, int minX, int maxX, int minY, int maxY) + private void GenerateRandomVertices(GraphExample graph, int index, int count, int minX, + int maxX, int minY, int maxY) { var list = graph.Vertices.ToList(); - var vertexPositions = new Dictionary(); for (var i = index; i < index + count; i++) { var vertex = list[i]; var vc = new VertexControl(vertex); erg_Area.AddVertex(vertex, vc); - vertexPositions[vertex] = new Point(ShowcaseHelper.Rand.Next(minX, maxX), ShowcaseHelper.Rand.Next(minY, maxY)); - vc.SetPosition(vertexPositions[vertex]); + var point = new Point(ShowcaseHelper.Rand.Next(minX, maxX), + ShowcaseHelper.Rand.Next(minY, maxY)); + vc.SetPosition(point); } - return vertexPositions; } - void erg_but_randomgraph_Click(object sender, RoutedEventArgs e) + private void erg_but_randomgraph_Click(object sender, RoutedEventArgs e) { - if ((EdgeRoutingAlgorithmTypeEnum)erg_eralgo.SelectedItem != EdgeRoutingAlgorithmTypeEnum.Bundling) { var gr = ShowcaseHelper.GenerateDataGraph(30); - if (erg_Area.LogicCore.EnableParallelEdges) + if (erg_Area.LogicCore!.EnableParallelEdges) { if (erg_Area.VertexList.Count() < 2) { - var v1 = new DataVertex(); gr.AddVertex(v1); - var v2 = new DataVertex(); gr.AddVertex(v2); - gr.AddEdge(new DataEdge(v1, v2) { Text = string.Format("{0} -> {1}", v1.Text, v2.Text) }); - gr.AddEdge(new DataEdge(v2, v1) { Text = string.Format("{0} -> {1}", v2.Text, v1.Text) }); + var v1 = new DataVertex(); + gr.AddVertex(v1); + var v2 = new DataVertex(); + gr.AddVertex(v2); + gr.AddEdge(new DataEdge(v1, v2) { Text = $"{v1.Text} -> {v2.Text}" }); + gr.AddEdge(new DataEdge(v2, v1) { Text = $"{v2.Text} -> {v1.Text}" }); } else { var v1 = gr.Vertices.ToList()[0]; var v2 = gr.Vertices.ToList()[1]; - gr.AddEdge(new DataEdge(v1, v2) { Text = string.Format("{0} -> {1}", v1.Text, v2.Text) }); - gr.AddEdge(new DataEdge(v2, v1) { Text = string.Format("{0} -> {1}", v2.Text, v1.Text) }); + gr.AddEdge(new DataEdge(v1, v2) { Text = $"{v1.Text} -> {v2.Text}" }); + gr.AddEdge(new DataEdge(v2, v1) { Text = $"{v2.Text} -> {v1.Text}" }); } } - erg_Area.GetLogicCore().DefaultEdgeRoutingAlgorithm = (EdgeRoutingAlgorithmTypeEnum)erg_eralgo.SelectedItem; + erg_Area.GetLogicCore().DefaultEdgeRoutingAlgorithm = + (EdgeRoutingAlgorithmTypeEnum)erg_eralgo.SelectedItem; switch ((EdgeRoutingAlgorithmTypeEnum)erg_eralgo.SelectedItem) { case EdgeRoutingAlgorithmTypeEnum.SimpleER: - erg_Area.GetLogicCore().DefaultEdgeRoutingAlgorithmParams = SimpleErParameters; + erg_Area.GetLogicCore().DefaultEdgeRoutingAlgorithmParams = + SimpleErParameters; break; case EdgeRoutingAlgorithmTypeEnum.PathFinder: erg_Area.GetLogicCore().DefaultEdgeRoutingAlgorithmParams = PfErParameters; @@ -280,11 +314,15 @@ void erg_but_randomgraph_Click(object sender, RoutedEventArgs e) } erg_Area.GetLogicCore().DefaultLayoutAlgorithm = LayoutAlgorithmTypeEnum.SimpleRandom; - erg_Area.GetLogicCore().DefaultLayoutAlgorithmParams = new RandomLayoutAlgorithmParams() { Bounds = new Rect(0,0, 500, 500)}; - erg_Area.GetLogicCore().DefaultOverlapRemovalAlgorithm = OverlapRemovalAlgorithmTypeEnum.FSA; - erg_Area.GetLogicCore().DefaultOverlapRemovalAlgorithmParams = erg_Area.LogicCore.AlgorithmFactory.CreateOverlapRemovalParameters(OverlapRemovalAlgorithmTypeEnum.FSA); - - erg_Area.GenerateGraph(gr, true); + erg_Area.GetLogicCore().DefaultLayoutAlgorithmParams = + new RandomLayoutAlgorithmParams() { Bounds = new Rect(0, 0, 500, 500) }; + erg_Area.GetLogicCore().DefaultOverlapRemovalAlgorithm = + OverlapRemovalAlgorithmTypeEnum.FSA; + erg_Area.GetLogicCore().DefaultOverlapRemovalAlgorithmParams = + erg_Area.LogicCore.AlgorithmFactory.CreateOverlapRemovalParameters(OverlapRemovalAlgorithmTypeEnum + .FSA); + + erg_Area.GenerateGraph(gr); erg_Area.SetVerticesDrag(true, true); erg_Area.SetEdgesDrag(true); erg_zoomctrl.ZoomToFill(); @@ -304,36 +342,36 @@ void erg_but_randomgraph_Click(object sender, RoutedEventArgs e) { if (ShowcaseHelper.Rand.Next(0, 50) > 25) continue; var vertex2 = vlist[ShowcaseHelper.Rand.Next(0, graph.VertexCount - 1)]; - graph.AddEdge(new DataEdge(item, vertex2, ShowcaseHelper.Rand.Next(1, 50)) { ToolTipText = string.Format("{0} -> {1}", item, vertex2) }); + graph.AddEdge(new DataEdge(item, vertex2, ShowcaseHelper.Rand.Next(1, 50)) + { ToolTipText = $"{item} -> {vertex2}" }); } //generate vertices - var vertexPositions = GenerateRandomVertices(graph, 0, 40, 0, 2000, 0, 2000).ToDictionary(item => item.Key, item => item.Value); - foreach (var item in GenerateRandomVertices(graph, 40, 40, 5000, 7000, 3000, 4000)) - vertexPositions.Add(item.Key, item.Value); - foreach (var item in GenerateRandomVertices(graph, 80, 40, 500, 2500, 6000, 9000)) - vertexPositions.Add(item.Key, item.Value); - erg_Area.LogicCore.Graph = graph; + GenerateRandomVertices(graph, 0, 40, 0, 2000, 0, 2000); + GenerateRandomVertices(graph, 40, 40, 5000, 7000, 3000, 4000); + GenerateRandomVertices(graph, 80, 40, 500, 2500, 6000, 9000); + erg_Area.LogicCore!.Graph = graph; UpdateLayout(); erg_Area.SetVerticesDrag(true); _logicCore.DefaultLayoutAlgorithm = LayoutAlgorithmTypeEnum.Custom; _logicCore.DefaultEdgeRoutingAlgorithm = EdgeRoutingAlgorithmTypeEnum.Bundling; _logicCore.DefaultEdgeRoutingAlgorithmParams = BundleEdgeRoutingParameters; - erg_Area.GenerateGraph(true); + erg_Area.GenerateGraph(); erg_zoomctrl.ZoomToFill(); } #region INotifyPropertyChanged + public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { - if(PropertyChanged != null) - PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name)); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } + #endregion } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/EditorGraph.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/EditorGraph.xaml.cs index 9270f72..0a71b4b 100644 --- a/Examples/ShowcaseApp.WPF/Pages/EditorGraph.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/EditorGraph.xaml.cs @@ -12,7 +12,7 @@ namespace ShowcaseApp.WPF.Pages /// /// Interaction logic for DynamicGraph.xaml /// - public partial class EditorGraph: IDisposable + public partial class EditorGraph : IDisposable { private EditorOperationMode _opMode = EditorOperationMode.Select; private VertexControl _ecFrom; @@ -49,30 +49,30 @@ public EditorGraph() butSelect.IsChecked = true; } - void graphArea_EdgeSelected(object sender, EdgeSelectedEventArgs args) + private void graphArea_EdgeSelected(object sender, EdgeSelectedEventArgs args) { if (args.MouseArgs.LeftButton == MouseButtonState.Pressed && _opMode == EditorOperationMode.Delete) graphArea.RemoveEdge(args.EdgeControl.Edge as DataEdge, true); } - void graphArea_VertexSelected(object sender, VertexSelectedEventArgs args) + private void graphArea_VertexSelected(object sender, VertexSelectedEventArgs args) { - if(args.MouseArgs.LeftButton == MouseButtonState.Pressed) - { - switch (_opMode) - { - case EditorOperationMode.Edit: - CreateEdgeControl(args.VertexControl); - break; - case EditorOperationMode.Delete: - SafeRemoveVertex(args.VertexControl); - break; - default: - if (_opMode == EditorOperationMode.Select && args.Modifiers == ModifierKeys.Control) - SelectVertex(args.VertexControl); - break; - } - } + if (args.MouseArgs.LeftButton == MouseButtonState.Pressed) + { + switch (_opMode) + { + case EditorOperationMode.Edit: + CreateEdgeControl(args.VertexControl); + break; + case EditorOperationMode.Delete: + SafeRemoveVertex(args.VertexControl); + break; + default: + if (_opMode == EditorOperationMode.Select && args.Modifiers == ModifierKeys.Control) + SelectVertex(args.VertexControl); + break; + } + } } private static void SelectVertex(DependencyObject vc) @@ -89,7 +89,7 @@ private static void SelectVertex(DependencyObject vc) } } - void zoomCtrl_MouseDown(object sender, MouseButtonEventArgs e) + private void zoomCtrl_MouseDown(object sender, MouseButtonEventArgs e) { //create vertices and edges only in Edit mode if (e.LeftButton == MouseButtonState.Pressed) @@ -97,11 +97,12 @@ void zoomCtrl_MouseDown(object sender, MouseButtonEventArgs e) if (_opMode == EditorOperationMode.Edit) { var pos = zoomCtrl.TranslatePoint(e.GetPosition(zoomCtrl), graphArea); - pos.Offset(-22.5,-22.5); + pos.Offset(-22.5, -22.5); var vc = CreateVertexControl(pos); if (_ecFrom != null) CreateEdgeControl(vc); - }else if(_opMode == EditorOperationMode.Select) + } + else if (_opMode == EditorOperationMode.Select) { ClearSelectMode(true); } @@ -109,9 +110,9 @@ void zoomCtrl_MouseDown(object sender, MouseButtonEventArgs e) } - void ToolbarButton_Checked(object sender, RoutedEventArgs e) + private void ToolbarButton_Checked(object sender, RoutedEventArgs e) { - if(butDelete.IsChecked == true && ReferenceEquals(sender, butDelete)) + if (butDelete.IsChecked == true && ReferenceEquals(sender, butDelete)) { butEdit.IsChecked = false; butSelect.IsChecked = false; @@ -121,6 +122,7 @@ void ToolbarButton_Checked(object sender, RoutedEventArgs e) ClearSelectMode(); return; } + if (butEdit.IsChecked == true && ReferenceEquals(sender, butEdit)) { butDelete.IsChecked = false; @@ -130,6 +132,7 @@ void ToolbarButton_Checked(object sender, RoutedEventArgs e) ClearSelectMode(); return; } + if (butSelect.IsChecked == true && ReferenceEquals(sender, butSelect)) { butEdit.IsChecked = false; @@ -139,7 +142,6 @@ void ToolbarButton_Checked(object sender, RoutedEventArgs e) ClearEditMode(); graphArea.SetVerticesDrag(true, true); graphArea.SetEdgesDrag(true); - return; } } @@ -167,7 +169,8 @@ private void ClearEditMode() private VertexControl CreateVertexControl(Point position) { - var data = new DataVertex("Vertex " + (graphArea.VertexList.Count + 1)) { ImageId = ShowcaseHelper.Rand.Next(0, ThemedDataStorage.EditorImages.Count) }; + var data = new DataVertex("Vertex " + (graphArea.VertexList.Count + 1)) + { ImageId = ShowcaseHelper.Rand.Next(0, ThemedDataStorage.EditorImages.Count) }; var vc = new VertexControl(data); vc.SetPosition(position); graphArea.AddVertexAndData(data, vc, true); @@ -176,14 +179,15 @@ private VertexControl CreateVertexControl(Point position) private void CreateEdgeControl(VertexControl vc) { - if(_ecFrom == null) + if (_ecFrom == null) { _editorManager.CreateVirtualEdge(vc, vc.GetPosition()); _ecFrom = vc; HighlightBehaviour.SetHighlighted(_ecFrom, true); return; } - if(_ecFrom == vc) return; + + if (_ecFrom == vc) return; var data = new DataEdge((DataVertex)_ecFrom.Vertex, (DataVertex)vc.Vertex); var ec = new EdgeControl(_ecFrom, vc, data); @@ -202,12 +206,10 @@ private void SafeRemoveVertex(VertexControl vc) public void Dispose() { - if(_editorManager != null) + if (_editorManager != null) _editorManager.Dispose(); - if(graphArea != null) - graphArea.Dispose(); + if (graphArea != null) + graphArea.Dispose(); } } - - -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageData.xaml b/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageData.xaml index e9d066c..dc71e79 100644 --- a/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageData.xaml +++ b/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageData.xaml @@ -1,4 +1,4 @@ - /// Interaction logic for DebugGraph.xaml /// - public partial class FeaturesPageData : UserControl, INotifyPropertyChanged + public partial class FeaturesPageData : INotifyPropertyChanged { public FeaturesPageData() { @@ -19,7 +18,7 @@ public FeaturesPageData() protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; - if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageEdges.xaml b/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageEdges.xaml index 9bf6328..40f7cfb 100644 --- a/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageEdges.xaml +++ b/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageEdges.xaml @@ -1,4 +1,4 @@ - /// Interaction logic for DebugGraph.xaml /// - public partial class FeaturesPageEdges : UserControl, INotifyPropertyChanged + public partial class FeaturesPageEdges : INotifyPropertyChanged { public FeaturesPageEdges() { @@ -19,7 +18,7 @@ public FeaturesPageEdges() protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; - if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageLayouts.xaml b/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageLayouts.xaml index 0b10ec7..041c61c 100644 --- a/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageLayouts.xaml +++ b/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageLayouts.xaml @@ -1,4 +1,4 @@ - /// Interaction logic for DebugGraph.xaml /// - public partial class FeaturesPageLayouts : UserControl, INotifyPropertyChanged + public partial class FeaturesPageLayouts : INotifyPropertyChanged { public FeaturesPageLayouts() { @@ -19,7 +18,7 @@ public FeaturesPageLayouts() protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; - if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageTemplates.xaml b/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageTemplates.xaml index bb073da..3e3801c 100644 --- a/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageTemplates.xaml +++ b/Examples/ShowcaseApp.WPF/Pages/FeatureLists/FeaturesPageTemplates.xaml @@ -1,4 +1,4 @@ - /// Interaction logic for DebugGraph.xaml /// - public partial class FeaturesPageTemplates : UserControl, INotifyPropertyChanged + public partial class FeaturesPageTemplates : INotifyPropertyChanged { public FeaturesPageTemplates() { @@ -19,7 +18,7 @@ public FeaturesPageTemplates() protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; - if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/GeneralGraph.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/GeneralGraph.xaml.cs index f4c0998..dbb9808 100644 --- a/Examples/ShowcaseApp.WPF/Pages/GeneralGraph.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/GeneralGraph.xaml.cs @@ -19,7 +19,7 @@ namespace ShowcaseApp.WPF.Pages /// /// Interaction logic for GeneralGraph.xaml /// - public partial class GeneralGraph : UserControl + public partial class GeneralGraph { public GeneralGraph() { @@ -34,13 +34,15 @@ public GeneralGraph() gg_oralgo.SelectionChanged += gg_oralgo_SelectionChanged; gg_eralgo.SelectionChanged += gg_eralgo_SelectionChanged; - gg_layalgo.ItemsSource = Enum.GetValues(typeof(LayoutAlgorithmTypeEnum)).Cast(); + gg_layalgo.ItemsSource = Enum.GetValues().Cast(); gg_layalgo.SelectedItem = LayoutAlgorithmTypeEnum.KK; - gg_oralgo.ItemsSource = Enum.GetValues(typeof(OverlapRemovalAlgorithmTypeEnum)).Cast(); + gg_oralgo.ItemsSource = Enum.GetValues() + .Cast(); gg_oralgo.SelectedIndex = 0; - gg_eralgo.ItemsSource = Enum.GetValues(typeof(EdgeRoutingAlgorithmTypeEnum)).Cast(); + gg_eralgo.ItemsSource = Enum.GetValues() + .Cast(); gg_eralgo.SelectedItem = EdgeRoutingAlgorithmTypeEnum.SimpleER; gg_but_randomgraph.Click += gg_but_randomgraph_Click; @@ -52,7 +54,7 @@ public GeneralGraph() gg_Area.SetEdgesDrag(true); ggLogic.DefaultEdgeRoutingAlgorithm = EdgeRoutingAlgorithmTypeEnum.SimpleER; - ggLogic.EdgeCurvingEnabled = true; + ggLogic.EdgeCurvingEnabled = true; gg_Area.ShowAllEdgesArrows(); ZoomControl.SetViewFinderVisibility(gg_zoomctrl, Visibility.Visible); @@ -63,7 +65,7 @@ public GeneralGraph() Loaded += GG_Loaded; } - void GG_Loaded(object sender, RoutedEventArgs e) + private void GG_Loaded(object sender, RoutedEventArgs e) { GG_RegisterCommands(); } @@ -79,17 +81,20 @@ private bool GGRelayoutCommandCanExecute(object sender) private void GgRelayoutCommandExecute(object sender) { - if (gg_Area.LogicCore.AsyncAlgorithmCompute) + if (gg_Area.LogicCore!.AsyncAlgorithmCompute) gg_loader.Visibility = Visibility.Visible; gg_Area.RelayoutGraph(true); } + #endregion #region SaveStateCommand - private static readonly RoutedCommand SaveStateCommand = new RoutedCommand(); + + private static readonly RoutedCommand SaveStateCommand = new(); + private void SaveStateCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { - e.CanExecute = gg_Area.LogicCore.Graph != null && gg_Area.VertexList.Count > 0; + e.CanExecute = gg_Area.LogicCore!.Graph != null && gg_Area.VertexList.Count > 0; } private void SaveStateCommandExecute(object sender, ExecutedRoutedEventArgs e) @@ -98,10 +103,13 @@ private void SaveStateCommandExecute(object sender, ExecutedRoutedEventArgs e) gg_Area.StateStorage.RemoveState("exampleState"); gg_Area.StateStorage.SaveState("exampleState", "My example state"); } + #endregion #region LoadStateCommand - private static readonly RoutedCommand LoadStateCommand = new RoutedCommand(); + + private static readonly RoutedCommand LoadStateCommand = new(); + private void LoadStateCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = gg_Area.StateStorage.ContainsState("exampleState"); @@ -112,10 +120,13 @@ private void LoadStateCommandExecute(object sender, ExecutedRoutedEventArgs e) if (gg_Area.StateStorage.ContainsState("exampleState")) gg_Area.StateStorage.LoadState("exampleState"); } + #endregion #region SaveLayoutCommand - private static readonly RoutedCommand SaveLayoutCommand = new RoutedCommand(); + + private static readonly RoutedCommand SaveLayoutCommand = new(); + private void SaveLayoutCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = gg_Area.LogicCore.Graph != null && gg_Area.VertexList.Count > 0; @@ -123,17 +134,20 @@ private void SaveLayoutCommandCanExecute(object sender, CanExecuteRoutedEventArg private void SaveLayoutCommandExecute(object sender, ExecutedRoutedEventArgs e) { - var dlg = new SaveFileDialog { Filter = "All files|*.*", Title = "Select layout file name", FileName = "laytest.xml" }; + var dlg = new SaveFileDialog + { Filter = "All files|*.*", Title = "Select layout file name", FileName = "laytest.xml" }; if (dlg.ShowDialog() == true) { - FileServiceProviderWpf.SerializeDataToFile(dlg.FileName, gg_Area.ExtractSerializationData()); + FileServiceProviderWpf.SerializeDataToFile(dlg.FileName, gg_Area.ExtractSerializationData()); } } + #endregion #region LoadLayoutCommand - private static readonly RoutedCommand LoadLayoutCommand = new RoutedCommand(); + private static readonly RoutedCommand LoadLayoutCommand = new(); + private static void LoadLayoutCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; @@ -141,32 +155,38 @@ private static void LoadLayoutCommandCanExecute(object sender, CanExecuteRoutedE private void LoadLayoutCommandExecute(object sender, ExecutedRoutedEventArgs e) { - var dlg = new OpenFileDialog { Filter = "All files|*.*", Title = "Select layout file", FileName = "laytest.xml" }; + var dlg = new OpenFileDialog + { Filter = "All files|*.*", Title = "Select layout file", FileName = "laytest.xml" }; if (dlg.ShowDialog() != true) return; try { - gg_Area.RebuildFromSerializationData(FileServiceProviderWpf.DeserializeDataFromFile(dlg.FileName)); + gg_Area.RebuildFromSerializationData(FileServiceProviderWpf.DeserializeDataFromFile(dlg.FileName)); gg_Area.SetVerticesDrag(true, true); gg_Area.UpdateAllEdges(); gg_zoomctrl.ZoomToFill(); } catch (Exception ex) { - MessageBox.Show(string.Format("Failed to load layout file:\n {0}", ex)); + MessageBox.Show($"Failed to load layout file:\n {ex}"); } } + #endregion - void GG_RegisterCommands() + private void GG_RegisterCommands() { - CommandBindings.Add(new CommandBinding(SaveStateCommand, SaveStateCommandExecute, SaveStateCommandCanExecute)); + CommandBindings.Add(new CommandBinding(SaveStateCommand, SaveStateCommandExecute, + SaveStateCommandCanExecute)); gg_saveState.Command = SaveStateCommand; - CommandBindings.Add(new CommandBinding(LoadStateCommand, LoadStateCommandExecute, LoadStateCommandCanExecute)); + CommandBindings.Add(new CommandBinding(LoadStateCommand, LoadStateCommandExecute, + LoadStateCommandCanExecute)); gg_loadState.Command = LoadStateCommand; - CommandBindings.Add(new CommandBinding(SaveLayoutCommand, SaveLayoutCommandExecute, SaveLayoutCommandCanExecute)); + CommandBindings.Add(new CommandBinding(SaveLayoutCommand, SaveLayoutCommandExecute, + SaveLayoutCommandCanExecute)); gg_saveLayout.Command = SaveLayoutCommand; - CommandBindings.Add(new CommandBinding(LoadLayoutCommand, LoadLayoutCommandExecute, LoadLayoutCommandCanExecute)); + CommandBindings.Add(new CommandBinding(LoadLayoutCommand, LoadLayoutCommandExecute, + LoadLayoutCommandCanExecute)); gg_loadLayout.Command = LoadLayoutCommand; gg_but_relayout.Command = new SimpleCommand(GGRelayoutCommandCanExecute, GgRelayoutCommandExecute); @@ -174,14 +194,14 @@ void GG_RegisterCommands() #endregion - void gg_async_Checked(object sender, RoutedEventArgs e) + private void gg_async_Checked(object sender, RoutedEventArgs e) { gg_Area.LogicCore.AsyncAlgorithmCompute = gg_async.IsChecked != null; } private void gg_saveAsPngImage_Click(object sender, RoutedEventArgs e) { - gg_Area.ExportAsImageDialog(ImageType.PNG, true, 96D, 100); + gg_Area.ExportAsImageDialog(ImageType.PNG, true); } private void gg_printlay_Click(object sender, RoutedEventArgs e) @@ -191,7 +211,8 @@ private void gg_printlay_Click(object sender, RoutedEventArgs e) private void gg_vertexCount_PreviewTextInput(object sender, TextCompositionEventArgs e) { - e.Handled = CustomHelper.IsIntegerInput(e.Text) && Convert.ToInt32(e.Text) <= ShowcaseHelper.DATASOURCE_SIZE; + e.Handled = CustomHelper.IsIntegerInput(e.Text) && + Convert.ToInt32(e.Text) <= ShowcaseHelper.DATASOURCE_SIZE; } private void gg_layalgo_SelectionChanged(object sender, SelectionChangedEventArgs e) @@ -200,7 +221,9 @@ private void gg_layalgo_SelectionChanged(object sender, SelectionChangedEventArg gg_Area.LogicCore.DefaultLayoutAlgorithm = late; if (late == LayoutAlgorithmTypeEnum.EfficientSugiyama) { - var prms = gg_Area.LogicCore.AlgorithmFactory.CreateLayoutParameters(LayoutAlgorithmTypeEnum.EfficientSugiyama) as EfficientSugiyamaLayoutParameters; + var prms = + gg_Area.LogicCore.AlgorithmFactory.CreateLayoutParameters(LayoutAlgorithmTypeEnum.EfficientSugiyama) + as EfficientSugiyamaLayoutParameters; prms.EdgeRouting = SugiyamaEdgeRoutings.Orthogonal; prms.LayerDistance = prms.VertexDistance = 100; gg_Area.LogicCore.EdgeCurvingEnabled = false; @@ -211,6 +234,7 @@ private void gg_layalgo_SelectionChanged(object sender, SelectionChangedEventArg { gg_Area.LogicCore.EdgeCurvingEnabled = true; } + if (late == LayoutAlgorithmTypeEnum.BoundedFR) gg_Area.LogicCore.DefaultLayoutAlgorithmParams = gg_Area.LogicCore.AlgorithmFactory.CreateLayoutParameters(LayoutAlgorithmTypeEnum.BoundedFR); @@ -223,7 +247,8 @@ private void gg_useExternalLayAlgo_Checked(object sender, RoutedEventArgs e) { if (gg_useExternalLayAlgo.IsChecked == true) { - var graph = gg_Area.LogicCore.Graph ?? ShowcaseHelper.GenerateDataGraph(Convert.ToInt32(gg_vertexCount.Text)); + var graph = gg_Area.LogicCore.Graph ?? + ShowcaseHelper.GenerateDataGraph(Convert.ToInt32(gg_vertexCount.Text)); gg_Area.LogicCore.Graph = graph; AssignExternalLayoutAlgorithm(graph); } @@ -232,14 +257,16 @@ private void gg_useExternalLayAlgo_Checked(object sender, RoutedEventArgs e) private void AssignExternalLayoutAlgorithm(BidirectionalGraph graph) { - gg_Area.LogicCore.ExternalLayoutAlgorithm = gg_Area.LogicCore.AlgorithmFactory.CreateLayoutAlgorithm(LayoutAlgorithmTypeEnum.ISOM, graph); + gg_Area.LogicCore.ExternalLayoutAlgorithm = + gg_Area.LogicCore.AlgorithmFactory.CreateLayoutAlgorithm(LayoutAlgorithmTypeEnum.ISOM, graph); } private void gg_oralgo_SelectionChanged(object sender, SelectionChangedEventArgs e) { var core = gg_Area.LogicCore; core.DefaultOverlapRemovalAlgorithm = (OverlapRemovalAlgorithmTypeEnum)gg_oralgo.SelectedItem; - if (core.DefaultOverlapRemovalAlgorithm == OverlapRemovalAlgorithmTypeEnum.FSA || core.DefaultOverlapRemovalAlgorithm == OverlapRemovalAlgorithmTypeEnum.OneWayFSA) + if (core.DefaultOverlapRemovalAlgorithm == OverlapRemovalAlgorithmTypeEnum.FSA || + core.DefaultOverlapRemovalAlgorithm == OverlapRemovalAlgorithmTypeEnum.OneWayFSA) { core.DefaultOverlapRemovalAlgorithmParams.HorizontalGap = 30; core.DefaultOverlapRemovalAlgorithmParams.VerticalGap = 30; @@ -248,21 +275,25 @@ private void gg_oralgo_SelectionChanged(object sender, SelectionChangedEventArgs private void gg_useExternalORAlgo_Checked(object sender, RoutedEventArgs e) { - gg_Area.LogicCore.ExternalOverlapRemovalAlgorithm = gg_useExternalORAlgo.IsChecked == true ? gg_Area.LogicCore.AlgorithmFactory.CreateOverlapRemovalAlgorithm(OverlapRemovalAlgorithmTypeEnum.FSA, null) : null; + gg_Area.LogicCore.ExternalOverlapRemovalAlgorithm = gg_useExternalORAlgo.IsChecked == true + ? gg_Area.LogicCore.AlgorithmFactory.CreateOverlapRemovalAlgorithm(OverlapRemovalAlgorithmTypeEnum.FSA, + null) + : null; } private void gg_eralgo_SelectionChanged(object sender, SelectionChangedEventArgs e) { gg_Area.LogicCore.DefaultEdgeRoutingAlgorithm = (EdgeRoutingAlgorithmTypeEnum)gg_eralgo.SelectedItem; - if ((EdgeRoutingAlgorithmTypeEnum) gg_eralgo.SelectedItem == EdgeRoutingAlgorithmTypeEnum.Bundling) + if ((EdgeRoutingAlgorithmTypeEnum)gg_eralgo.SelectedItem == EdgeRoutingAlgorithmTypeEnum.Bundling) { - BundleEdgeRoutingParameters prm = new BundleEdgeRoutingParameters(); + var prm = new BundleEdgeRoutingParameters(); gg_Area.LogicCore.DefaultEdgeRoutingAlgorithmParams = prm; prm.Iterations = 200; prm.SpringConstant = 5; prm.Threshold = .1f; gg_Area.LogicCore.EdgeCurvingEnabled = true; - }else + } + else gg_Area.LogicCore.EdgeCurvingEnabled = false; } @@ -270,14 +301,17 @@ private void gg_useExternalERAlgo_Checked(object sender, RoutedEventArgs e) { if (gg_useExternalERAlgo.IsChecked == true) { - var graph = gg_Area.LogicCore.Graph ?? ShowcaseHelper.GenerateDataGraph(Convert.ToInt32(gg_vertexCount.Text)); + var graph = gg_Area.LogicCore.Graph ?? + ShowcaseHelper.GenerateDataGraph(Convert.ToInt32(gg_vertexCount.Text)); gg_Area.LogicCore.Graph = graph; - gg_Area.GetLogicCore().ExternalEdgeRoutingAlgorithm = gg_Area.LogicCore.AlgorithmFactory.CreateEdgeRoutingAlgorithm(EdgeRoutingAlgorithmTypeEnum.SimpleER, new Rect(gg_Area.DesiredSize.ToGraphX()), graph, null, null); + gg_Area.GetLogicCore().ExternalEdgeRoutingAlgorithm = + gg_Area.LogicCore.AlgorithmFactory.CreateEdgeRoutingAlgorithm(EdgeRoutingAlgorithmTypeEnum.SimpleER, + new Rect(gg_Area.DesiredSize.ToGraphX()), graph, null, null); } else gg_Area.GetLogicCore().ExternalEdgeRoutingAlgorithm = null; } - void gg_Area_RelayoutFinished(object sender, EventArgs e) + private void gg_Area_RelayoutFinished(object sender, EventArgs e) { if (gg_Area.LogicCore.AsyncAlgorithmCompute) gg_loader.Visibility = Visibility.Collapsed; @@ -288,9 +322,9 @@ void gg_Area_RelayoutFinished(object sender, EventArgs e) /// /// Use this event in case we have chosen async computation /// - void gg_Area_GenerateGraphFinished(object sender, EventArgs e) + private void gg_Area_GenerateGraphFinished(object sender, EventArgs e) { - if(!gg_Area.EdgesList.Any()) + if (!gg_Area.EdgesList.Any()) gg_Area.GenerateAllEdges(); if (gg_Area.LogicCore.AsyncAlgorithmCompute) gg_loader.Visibility = Visibility.Collapsed; @@ -319,6 +353,7 @@ private void gg_but_randomgraph_Click(object sender, RoutedEventArgs e) graph = ShowcaseHelper.GenerateDataGraph(Convert.ToInt32(gg_vertexCount.Text), true, mult); break; } + //add self loop graph.AddEdge(new DataEdge(graph.Vertices.First(), graph.Vertices.First())); @@ -334,4 +369,4 @@ private void gg_but_randomgraph_Click(object sender, RoutedEventArgs e) gg_Area.GenerateGraph(graph); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/Introduction.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/Introduction.xaml.cs index 28420c0..11f4454 100644 --- a/Examples/ShowcaseApp.WPF/Pages/Introduction.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/Introduction.xaml.cs @@ -1,11 +1,9 @@ -using System.Windows.Controls; - -namespace ShowcaseApp.WPF.Pages +namespace ShowcaseApp.WPF.Pages { /// /// Interaction logic for Introduction.xaml /// - public partial class Introduction : UserControl + public partial class Introduction { public Introduction() { diff --git a/Examples/ShowcaseApp.WPF/Pages/Mini/DataFiltering.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/Mini/DataFiltering.xaml.cs index 1f43428..daa31a5 100644 --- a/Examples/ShowcaseApp.WPF/Pages/Mini/DataFiltering.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/Mini/DataFiltering.xaml.cs @@ -13,16 +13,15 @@ namespace ShowcaseApp.WPF.Pages.Mini /// /// Interaction logic for LayoutVCP.xaml /// - public partial class DataFiltering : UserControl, INotifyPropertyChanged + public partial class DataFiltering : INotifyPropertyChanged { - public DataFiltering() { InitializeComponent(); DataContext = this; Loaded += ControlLoaded; - cboxFilter.ItemsSource = new List {"None", "Only yellow vertices", "Only blue vertices"}; + cboxFilter.ItemsSource = new List { "None", "Only yellow vertices", "Only blue vertices" }; cboxFilter.SelectedIndex = 0; cboxFilter.SelectionChanged += CboxFilter_SelectionChanged; } @@ -32,13 +31,12 @@ private void CboxFilter_SelectionChanged(object sender, SelectionChangedEventArg graphArea.LogicCore.Filters.Clear(); if (cboxFilter.SelectedIndex == 1) graphArea.LogicCore.Filters.Enqueue(new YellowVertexFilter()); - else if(cboxFilter.SelectedIndex == 2) + else if (cboxFilter.SelectedIndex == 2) graphArea.LogicCore.Filters.Enqueue(new BlueVertexFilter()); graphArea.RelayoutGraph(); - } - void ControlLoaded(object sender, RoutedEventArgs e) + private void ControlLoaded(object sender, RoutedEventArgs e) { GenerateGraph(); } @@ -52,7 +50,8 @@ private void GenerateGraph() DefaultEdgeRoutingAlgorithm = EdgeRoutingAlgorithmTypeEnum.SimpleER, DefaultLayoutAlgorithm = LayoutAlgorithmTypeEnum.SimpleRandom }; - graphArea.LogicCore.Graph.Vertices.ToList().ForEach(a=> a.IsBlue = Convert.ToBoolean(ShowcaseHelper.Rand.Next(2))); + graphArea.LogicCore.Graph.Vertices.ToList() + .ForEach(a => a.IsBlue = Convert.ToBoolean(ShowcaseHelper.Rand.Next(2))); //settings //gen graph @@ -71,4 +70,4 @@ protected virtual void OnPropertyChanged(string propertyName) handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/Mini/EdgesParallel.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/Mini/EdgesParallel.xaml.cs index dcce4b5..b79f095 100644 --- a/Examples/ShowcaseApp.WPF/Pages/Mini/EdgesParallel.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/Mini/EdgesParallel.xaml.cs @@ -2,8 +2,6 @@ using System.ComponentModel; using System.Linq; using System.Windows; -using System.Windows.Controls; -using Westermo.GraphX.Controls; using Westermo.GraphX.Controls.Models; using Westermo.GraphX.Common.Enums; using ShowcaseApp.WPF.Models; @@ -13,24 +11,28 @@ namespace ShowcaseApp.WPF.Pages.Mini /// /// Interaction logic for LayoutVCP.xaml /// - public partial class EdgesParallel : UserControl, INotifyPropertyChanged + public partial class EdgesParallel : INotifyPropertyChanged { private int _edgeDistance; - public int EdgeDistance { get { return _edgeDistance; } - set - { + + public int EdgeDistance + { + get => _edgeDistance; + set + { _edgeDistance = value; - graphArea.LogicCore.ParallelEdgeDistance = value; + graphArea.LogicCore.ParallelEdgeDistance = value; graphArea.UpdateAllEdges(true); - OnPropertyChanged("EdgeDistance"); - } } + OnPropertyChanged("EdgeDistance"); + } + } public EdgesParallel() { InitializeComponent(); DataContext = this; Loaded += ControlLoaded; - + cbEnablePE.IsChecked = true; _edgeDistance = 10; @@ -41,11 +43,11 @@ public EdgesParallel() private void CbMathShapeOnChecked(object sender, RoutedEventArgs routedEventArgs) { - graphArea.LogicCore.EnableParallelEdges = (bool) cbEnablePE.IsChecked; + graphArea.LogicCore.EnableParallelEdges = (bool)cbEnablePE.IsChecked; graphArea.UpdateAllEdges(true); } - void ControlLoaded(object sender, RoutedEventArgs e) + private void ControlLoaded(object sender, RoutedEventArgs e) { OnPropertyChanged("EdgeDistance"); GenerateGraph(); @@ -71,9 +73,9 @@ private void GenerateGraph() //set positions var posList = new Dictionary() { - {vList[0], new Point(0, -150)}, - {vList[1], new Point(300, 0)}, - {vList[2], new Point(600, -150)}, + { vList[0], new Point(0, -150) }, + { vList[1], new Point(300, 0) }, + { vList[2], new Point(600, -150) }, }; //settings @@ -94,8 +96,8 @@ private void GenerateGraph() eList[1].GetLabelControls().FirstOrDefault().LabelVerticalOffset = 12; eList[2].GetLabelControls().FirstOrDefault().ShowLabel = false; - // eList[3].GetLabelControls().FirstOrDefault().LabelVerticalOffset = 12; - // eList[4].GetLabelControls().FirstOrDefault().LabelVerticalOffset = -12; + // eList[3].GetLabelControls().FirstOrDefault().LabelVerticalOffset = 12; + // eList[4].GetLabelControls().FirstOrDefault().LabelVerticalOffset = -12; //PS: to see how parallel edges logic works go to GraphArea::UpdateParallelEdgesData() method @@ -107,7 +109,7 @@ private void GenerateGraph() protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; - if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/Mini/LayoutGrouped.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/Mini/LayoutGrouped.xaml.cs index 3139db8..19f8a01 100644 --- a/Examples/ShowcaseApp.WPF/Pages/Mini/LayoutGrouped.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/Mini/LayoutGrouped.xaml.cs @@ -17,7 +17,7 @@ namespace ShowcaseApp.WPF.Pages.Mini /// /// Interaction logic for LayoutVCP.xaml /// - public partial class LayoutGrouped : UserControl + public partial class LayoutGrouped { public LayoutGrouped() { @@ -27,7 +27,7 @@ public LayoutGrouped() graphArea.SideExpansionSize = new Size(80, 80); } - void ControlLoaded(object sender, RoutedEventArgs e) + private void ControlLoaded(object sender, RoutedEventArgs e) { GenerateGraph(); } @@ -45,7 +45,7 @@ private void GenerateGraph() //generate group params var prms = new List> { - new AlgorithmGroupParameters + new() { GroupId = 1, LayoutAlgorithm = @@ -53,7 +53,7 @@ private void GenerateGraph() new RandomLayoutAlgorithmParams {Bounds = new Rect(10, 10, 490, 490)}), }, - new AlgorithmGroupParameters + new() { GroupId = 2, LayoutAlgorithm = @@ -87,8 +87,8 @@ private void GenerateGraph() zoomControl.ZoomToFill(); } - private double _headerHeight = 30; - private double _groupInnerPadding = 20; + private readonly double _headerHeight = 30; + private readonly double _groupInnerPadding = 20; private Border GenerateGroupBorder(AlgorithmGroupParameters prms) { @@ -109,7 +109,7 @@ private Border GenerateGroupBorder(AlgorithmGroupParameters /// Interaction logic for LayoutVCP.xaml /// - public partial class LayoutVCP : UserControl + public partial class LayoutVCP { public LayoutVCP() { @@ -29,15 +29,14 @@ private void ButAddVcp_Click(object sender, RoutedEventArgs e) var vc = graphArea.VertexList.Values.ToList()[rdNum]; //create new VCP with container var newId = vc.VertexConnectionPointsList.Last().Id + 1; - var vcp = new StaticVertexConnectionPoint {Id = newId}; - var ctrl = new Border { Margin = new Thickness(2,2,0,2), Padding = new Thickness(0), Child = vcp }; + var vcp = new StaticVertexConnectionPoint { Id = newId }; + var ctrl = new Border { Margin = new Thickness(2, 2, 0, 2), Padding = new Thickness(0), Child = vcp }; //add vcp to the root container //in order to be able to use VCPRoot property we must specify container in the XAML template through PART_vcproot name vc.VCPRoot.Children.Add(ctrl); vc.VertexConnectionPointsList.Add(vcp); //update edge to use new connection point - var ec = graphArea.GetRelatedEdgeControls(vc, EdgesType.Out).First() as EdgeControl; - if (ec == null) + if (graphArea.GetRelatedEdgeControls(vc, EdgesType.Out).First() is not EdgeControl ec) { ec = graphArea.GetRelatedEdgeControls(vc, EdgesType.In).First() as EdgeControl; (ec.Edge as DataEdge).TargetConnectionPointId = newId; @@ -46,19 +45,20 @@ private void ButAddVcp_Click(object sender, RoutedEventArgs e) { (ec.Edge as DataEdge).SourceConnectionPointId = newId; } + graphArea.EdgesList[ec.Edge as DataEdge].UpdateEdge(); //graphArea.UpdateAllEdges(true); - } private void CbMathShapeOnChecked(object sender, RoutedEventArgs routedEventArgs) { - foreach(var item in graphArea.VertexList.Values) - item.VertexConnectionPointsList.ForEach(a => a.Shape = cbMathShape.IsChecked == true ? VertexShape.Circle : VertexShape.None); + foreach (var item in graphArea.VertexList.Values) + item.VertexConnectionPointsList.ForEach(a => + a.Shape = cbMathShape.IsChecked == true ? VertexShape.Circle : VertexShape.None); graphArea.UpdateAllEdges(true); } - void ControlLoaded(object sender, RoutedEventArgs e) + private void ControlLoaded(object sender, RoutedEventArgs e) { GenerateGraph(); } @@ -88,12 +88,12 @@ private void GenerateGraph() //set positions var posList = new Dictionary() { - {vList[0], new Point(0, 0)}, - {vList[1], new Point(200, -200)}, - {vList[2], new Point(200, 200)}, - {vList[3], new Point(600, -300)}, - {vList[4], new Point(600, 300)}, - {vList[5], new Point(400, 0)}, + { vList[0], new Point(0, 0) }, + { vList[1], new Point(200, -200) }, + { vList[2], new Point(200, 200) }, + { vList[3], new Point(600, -300) }, + { vList[4], new Point(600, 300) }, + { vList[5], new Point(400, 0) }, }; graphArea.PreloadGraph(posList); @@ -104,4 +104,4 @@ private void GenerateGraph() zoomControl.ZoomToFill(); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/NNGraph.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/NNGraph.xaml.cs index b526ae8..f5b0072 100644 --- a/Examples/ShowcaseApp.WPF/Pages/NNGraph.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/NNGraph.xaml.cs @@ -14,16 +14,16 @@ namespace ShowcaseApp.WPF.Pages /// /// Interaction logic for DynamicGraph.xaml /// - public partial class NNGraph: IDisposable + public partial class NNGraph : IDisposable { /// /// tmp collection to speedup selected vertices search /// - private readonly List _selectedVertices = new List(); + private readonly List _selectedVertices = []; private EditorOperationMode _opMode = EditorOperationMode.Select; private VertexControl _ecFrom; - private EditorObjectManager _editorManager; + private readonly EditorObjectManager _editorManager; public NNGraph() { @@ -53,10 +53,9 @@ public NNGraph() butEdit.Checked += ToolbarButton_Checked; butSelect.IsChecked = true; - } - void graphArea_EdgeSelected(object sender, EdgeSelectedEventArgs args) + private void graphArea_EdgeSelected(object sender, EdgeSelectedEventArgs args) { if (args.MouseArgs.LeftButton == MouseButtonState.Pressed && _opMode == EditorOperationMode.Delete) { @@ -65,17 +64,17 @@ void graphArea_EdgeSelected(object sender, EdgeSelectedEventArgs args) } } - void graphArea_VertexSelected(object sender, VertexSelectedEventArgs args) + private void graphArea_VertexSelected(object sender, VertexSelectedEventArgs args) { - if(args.MouseArgs.LeftButton == MouseButtonState.Pressed) - { - if (_opMode == EditorOperationMode.Edit) + if (args.MouseArgs.LeftButton == MouseButtonState.Pressed) + { + if (_opMode == EditorOperationMode.Edit) CreateEdgeControl(args.VertexControl); - else if(_opMode == EditorOperationMode.Delete) - SafeRemoveVertex(args.VertexControl); - else if (_opMode == EditorOperationMode.Select && args.Modifiers == ModifierKeys.Control) - SelectVertex(args.VertexControl); - } + else if (_opMode == EditorOperationMode.Delete) + SafeRemoveVertex(args.VertexControl); + else if (_opMode == EditorOperationMode.Select && args.Modifiers == ModifierKeys.Control) + SelectVertex(args.VertexControl); + } } private void SelectVertex(VertexControl vc) @@ -94,7 +93,7 @@ private void SelectVertex(VertexControl vc) } } - void zoomCtrl_MouseDown(object sender, MouseButtonEventArgs e) + private void zoomCtrl_MouseDown(object sender, MouseButtonEventArgs e) { //create vertices and edges only in Edit mode if (e.LeftButton == MouseButtonState.Pressed) @@ -102,11 +101,12 @@ void zoomCtrl_MouseDown(object sender, MouseButtonEventArgs e) if (_opMode == EditorOperationMode.Edit) { var pos = zoomCtrl.TranslatePoint(e.GetPosition(zoomCtrl), graphArea); - pos.Offset(-22.5,-22.5); + pos.Offset(-22.5, -22.5); var vc = CreateVertexControl(pos); if (_ecFrom != null) CreateEdgeControl(vc); - }else if(_opMode == EditorOperationMode.Select) + } + else if (_opMode == EditorOperationMode.Select) { ClearSelectMode(true); } @@ -114,9 +114,9 @@ void zoomCtrl_MouseDown(object sender, MouseButtonEventArgs e) } - void ToolbarButton_Checked(object sender, RoutedEventArgs e) + private void ToolbarButton_Checked(object sender, RoutedEventArgs e) { - if(butDelete.IsChecked == true && ReferenceEquals(sender, butDelete)) + if (butDelete.IsChecked == true && ReferenceEquals(sender, butDelete)) { butEdit.IsChecked = false; butSelect.IsChecked = false; @@ -126,6 +126,7 @@ void ToolbarButton_Checked(object sender, RoutedEventArgs e) ClearSelectMode(); return; } + if (butEdit.IsChecked == true && ReferenceEquals(sender, butEdit)) { butDelete.IsChecked = false; @@ -135,6 +136,7 @@ void ToolbarButton_Checked(object sender, RoutedEventArgs e) ClearSelectMode(); return; } + if (butSelect.IsChecked == true && ReferenceEquals(sender, butSelect)) { butEdit.IsChecked = false; @@ -143,7 +145,6 @@ void ToolbarButton_Checked(object sender, RoutedEventArgs e) _opMode = EditorOperationMode.Select; ClearEditMode(); graphArea.SetVerticesDrag(true, true); - return; } } @@ -158,6 +159,7 @@ private void ClearSelectMode(bool soft = false) }); _selectedVertices.Clear(); } + if (!soft) { graphArea.SetVerticesDrag(false); @@ -173,28 +175,30 @@ private void ClearEditMode() private VertexControl CreateVertexControl(Point position) { - var data = new DataVertex("Vertex " + (graphArea.VertexList.Count + 1)) { ImageId = ShowcaseHelper.Rand.Next(0, ThemedDataStorage.EditorImages.Count) }; + var data = new DataVertex("Vertex " + (graphArea.VertexList.Count + 1)) + { ImageId = ShowcaseHelper.Rand.Next(0, ThemedDataStorage.EditorImages.Count) }; graphArea.LogicCore.Graph.AddVertex(data); var vc = new VertexControl(data); graphArea.AddVertex(data, vc); - GraphAreaBase.SetX(vc, position.X, true); + GraphAreaBase.SetX(vc, position.X); GraphAreaBase.SetY(vc, position.Y, true); return vc; } private void CreateEdgeControl(VertexControl vc) { - if(_ecFrom == null) + if (_ecFrom == null) { _editorManager.CreateVirtualEdge(vc, vc.GetPosition()); _ecFrom = vc; HighlightBehaviour.SetHighlighted(_ecFrom, true); return; } - if(_ecFrom == vc) return; + + if (_ecFrom == vc) return; var data = new DataEdge((DataVertex)_ecFrom.Vertex, (DataVertex)vc.Vertex); - graphArea.LogicCore.Graph.AddEdge(data); + graphArea.LogicCore!.Graph.AddEdge(data); var ec = new EdgeControl(_ecFrom, vc, data); graphArea.InsertEdge(data, ec); @@ -206,26 +210,27 @@ private void CreateEdgeControl(VertexControl vc) private void SafeRemoveVertex(VertexControl vc, bool removeFromSelected = false) { //remove all adjacent edges - foreach (var ec in graphArea.GetRelatedControls(vc, GraphControlType.Edge, EdgesType.All).OfType()) + foreach (var ec in graphArea.GetRelatedControls(vc, GraphControlType.Edge, EdgesType.All) + .OfType()) { - graphArea.LogicCore.Graph.RemoveEdge(ec.Edge as DataEdge); - graphArea.RemoveEdge(ec.Edge as DataEdge); + if (ec.Edge is not DataEdge dataEdge) continue; + graphArea.LogicCore!.Graph.RemoveEdge(dataEdge); + graphArea.RemoveEdge(dataEdge); } - graphArea.LogicCore.Graph.RemoveVertex(vc.Vertex as DataVertex); - graphArea.RemoveVertex(vc.Vertex as DataVertex); + + if (vc.Vertex is not DataVertex dataVertex) return; + graphArea.LogicCore!.Graph.RemoveVertex(dataVertex); + graphArea.RemoveVertex(dataVertex); if (removeFromSelected && _selectedVertices.Contains(vc)) _selectedVertices.Remove(vc); } public void Dispose() { - if(_editorManager != null) + if (_editorManager != null) _editorManager.Dispose(); - if(graphArea != null) + if (graphArea != null) graphArea.Dispose(); - } } - - -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/Settings.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/Settings.xaml.cs index a4db0d5..195eb60 100644 --- a/Examples/ShowcaseApp.WPF/Pages/Settings.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/Settings.xaml.cs @@ -1,15 +1,13 @@ -using System.Windows.Controls; - -namespace ShowcaseApp.WPF.Pages +namespace ShowcaseApp.WPF.Pages { /// /// Interaction logic for Settings.xaml /// - public partial class Settings : UserControl + public partial class Settings { public Settings() { InitializeComponent(); } } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/ThemedGraph.xaml b/Examples/ShowcaseApp.WPF/Pages/ThemedGraph.xaml index 6f0c454..d34644c 100644 --- a/Examples/ShowcaseApp.WPF/Pages/ThemedGraph.xaml +++ b/Examples/ShowcaseApp.WPF/Pages/ThemedGraph.xaml @@ -1,56 +1,59 @@  - - - + + + - - + + - + - + - - + + - + - + - + - + - + @@ -61,7 +64,7 @@ - + @@ -69,55 +72,77 @@ - - - + \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Pages/ThemedGraph.xaml.cs b/Examples/ShowcaseApp.WPF/Pages/ThemedGraph.xaml.cs index 4709d2c..f7ac7b7 100644 --- a/Examples/ShowcaseApp.WPF/Pages/ThemedGraph.xaml.cs +++ b/Examples/ShowcaseApp.WPF/Pages/ThemedGraph.xaml.cs @@ -15,9 +15,9 @@ namespace ShowcaseApp.WPF.Pages /// /// Interaction logic for ThemedGraph.xaml /// - public partial class ThemedGraph : INotifyPropertyChanged + public partial class ThemedGraph { - // private ZoomControl tg_zoomctrl = new ZoomControl(); + // private ZoomControl tg_zoomctrl = new ZoomControl(); public ThemedGraph() { @@ -37,37 +37,38 @@ public ThemedGraph() tg_edgeMode.ItemsSource = new[] { "Draw all", "Draw for selected" }; tg_edgeMode.SelectedIndex = 0; - tg_edgeType.ItemsSource = Enum.GetValues(typeof(EdgesType)).Cast(); + tg_edgeType.ItemsSource = Enum.GetValues().Cast(); tg_edgeType.SelectedItem = EdgesType.All; - tg_moveAnimation.ItemsSource = Enum.GetValues(typeof(MoveAnimation)).Cast(); + tg_moveAnimation.ItemsSource = Enum.GetValues().Cast(); tg_moveAnimation.SelectedItem = MoveAnimation.Move; - tg_deleteAnimation.ItemsSource = Enum.GetValues(typeof(DeleteAnimation)).Cast(); + tg_deleteAnimation.ItemsSource = Enum.GetValues().Cast(); tg_deleteAnimation.SelectedItem = DeleteAnimation.Shrink; - tg_mouseoverAnimation.ItemsSource = Enum.GetValues(typeof(MouseOverAnimation)).Cast(); + tg_mouseoverAnimation.ItemsSource = Enum.GetValues().Cast(); tg_mouseoverAnimation.SelectedItem = MouseOverAnimation.Scale; - tg_highlightType.ItemsSource = Enum.GetValues(typeof(GraphControlType)).Cast(); + tg_highlightType.ItemsSource = Enum.GetValues().Cast(); tg_highlightType.SelectedItem = GraphControlType.VertexAndEdge; - tg_highlightEdgeType.ItemsSource = Enum.GetValues(typeof(EdgesType)).Cast(); + tg_highlightEdgeType.ItemsSource = Enum.GetValues().Cast(); tg_highlightEdgeType.SelectedItem = EdgesType.All; - tg_highlightEnabled_Checked(null, null); - tg_dragMoveEdges_Checked(null, null); - tg_dragEnabled_Checked(null, null); + HighlightEnabledSelectionChanged(null, null); + DragMoveEdgesChecked(null, null); + DragEnabledChanged(null, null); - tg_Area.VertexSelected += tg_Area_VertexSelected; - tg_Area.GenerateGraphFinished += tg_Area_GenerateGraphFinished; - tg_Area.RelayoutFinished += tg_Area_RelayoutFinished; - tg_dragMoveEdges.Checked += tg_dragMoveEdges_Checked; - tg_dragMoveEdges.Unchecked += tg_dragMoveEdges_Checked; + tg_Area.VertexSelected += AreaVertexSelected; + tg_Area.GenerateGraphFinished += AreaGeneratedGraphFinished; + tg_Area.RelayoutFinished += AreaRelayoutFinished; + tg_dragMoveEdges.Checked += DragMoveEdgesChecked; + tg_dragMoveEdges.Unchecked += DragMoveEdgesChecked; ZoomControl.SetViewFinderVisibility(tg_zoomctrl, Visibility.Visible); - TgRegisterCommands(); + TgRegisterCommands(); } #region Commands #region TGRelayoutCommand + private static bool TgRelayoutCommandCanExecute(object sender) { return true; @@ -75,113 +76,115 @@ private static bool TgRelayoutCommandCanExecute(object sender) private void TgRelayoutCommandExecute(object sender) { - if (tg_Area.LogicCore.AsyncAlgorithmCompute) + if (tg_Area.LogicCore!.AsyncAlgorithmCompute) tg_loader.Visibility = Visibility.Visible; tg_Area.RelayoutGraph(true); } + #endregion - void TgRegisterCommands() + private void TgRegisterCommands() { tg_but_relayout.Command = new SimpleCommand(TgRelayoutCommandCanExecute, TgRelayoutCommandExecute); } + #endregion - void tg_Area_VertexSelected(object sender, VertexSelectedEventArgs args) + private void AreaVertexSelected(object sender, VertexSelectedEventArgs args) { - if (args.MouseArgs.LeftButton == MouseButtonState.Pressed && tg_edgeMode.SelectedIndex == 1) + if (args.MouseArgs!.LeftButton == MouseButtonState.Pressed && tg_edgeMode.SelectedIndex == 1) { tg_Area.GenerateEdgesForVertex(args.VertexControl, (EdgesType)tg_edgeType.SelectedItem); } + if (args.MouseArgs.RightButton != MouseButtonState.Pressed) return; args.VertexControl.ContextMenu = new ContextMenu(); var menuitem = new MenuItem { Header = "Delete item", Tag = args.VertexControl }; - menuitem.Click += tg_deleteitem_Click; + menuitem.Click += DeleteItemClick; args.VertexControl.ContextMenu.Items.Add(menuitem); args.VertexControl.ContextMenu.IsOpen = true; } - void tg_deleteitem_Click(object sender, RoutedEventArgs e) + private void DeleteItemClick(object sender, RoutedEventArgs e) { - var menuItem = sender as MenuItem; - if (menuItem == null) return; - var vc = menuItem.Tag as VertexControl; - if (vc == null) return; - tg_Area.RemoveVertexAndEdges(vc.Vertex as DataVertex); + if (sender is not MenuItem menuItem) return; + if (menuItem.Tag is not VertexControl vc) return; + if (vc.Vertex is not DataVertex vertex) return; + tg_Area.RemoveVertexAndEdges(vertex); } - private void tg_but_randomgraph_Click(object sender, RoutedEventArgs e) + private void ButRandomGraphClick(object sender, RoutedEventArgs e) { var graph = ShowcaseHelper.GenerateDataGraph(ShowcaseHelper.Rand.Next(10, 20)); foreach (var item in graph.Vertices) ThemedDataStorage.FillDataVertex(item); foreach (var item in graph.Edges) - item.ToolTipText = string.Format("{0} -> {1}", item.Source.Name, item.Target.Name); + item.ToolTipText = $"{item.Source.Name} -> {item.Target.Name}"; //TIP: trick to disable zoomcontrol behaviour when it is performing fill animation from top left zoomed corner //instead we will fill-animate from maximum zoom distance //tg_zoomctrl.Zoom = 0.01; //disable zoom control auto fill animation by setting this value tg_Area.GenerateGraph(graph, tg_edgeMode.SelectedIndex == 0); - if (tg_Area.LogicCore.AsyncAlgorithmCompute) + if (tg_Area.LogicCore!.AsyncAlgorithmCompute) tg_loader.Visibility = Visibility.Visible; } - void tg_Area_RelayoutFinished(object sender, EventArgs e) + private void AreaRelayoutFinished(object sender, EventArgs e) { - if (tg_Area.LogicCore.AsyncAlgorithmCompute) + if (tg_Area.LogicCore!.AsyncAlgorithmCompute) tg_loader.Visibility = Visibility.Collapsed; - if(tg_Area.MoveAnimation == null) - tg_zoomctrl.ZoomToFill(); + if (tg_Area.MoveAnimation == null) + tg_zoomctrl.ZoomToFill(); } - void tg_Area_GenerateGraphFinished(object sender, EventArgs e) + private void AreaGeneratedGraphFinished(object sender, EventArgs e) { - if (tg_Area.LogicCore.AsyncAlgorithmCompute) + if (tg_Area.LogicCore!.AsyncAlgorithmCompute) tg_loader.Visibility = Visibility.Collapsed; - tg_highlightType_SelectionChanged(null, null); - tg_highlightEnabled_Checked(null, null); - tg_highlightEdgeType_SelectionChanged(null, null); - tg_dragMoveEdges_Checked(null, null); - tg_dragEnabled_Checked(null, null); + HighlightTypeSelectionChanged(null, null); + HighlightEnabledSelectionChanged(null, null); + HighlightEdgeTypeSelectionChanged(null, null); + DragMoveEdgesChecked(null, null); + DragEnabledChanged(null, null); tg_Area.SetEdgesDashStyle(EdgeDashStyle.Dash); - tg_zoomctrl.ZoomToFill();// ZoomToFill(); //manually update zoom control to fill the area + tg_zoomctrl.ZoomToFill(); // ZoomToFill(); //manually update zoom control to fill the area } - private void tg_edgeMode_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void EdgeModeSelectionChanged(object sender, SelectionChangedEventArgs e) { - } - private void tg_edgeType_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void EdgeTypeSelectionChanged(object sender, SelectionChangedEventArgs e) { - } - void tg_dragMoveEdges_Checked(object sender, RoutedEventArgs e) + private void DragMoveEdgesChecked(object sender, RoutedEventArgs e) { foreach (var item in tg_Area.VertexList) - DragBehaviour.SetUpdateEdgesOnMove(item.Value, tg_dragMoveEdges.IsChecked != null && tg_dragMoveEdges.IsChecked.Value); + DragBehaviour.SetUpdateEdgesOnMove(item.Value, + tg_dragMoveEdges.IsChecked != null && tg_dragMoveEdges.IsChecked.Value); } - private void tg_dragEnabled_Checked(object sender, RoutedEventArgs e) + private void DragEnabledChanged(object sender, RoutedEventArgs e) { if (tg_dragEnabled.IsChecked == null) return; tg_dragMoveEdges.IsEnabled = (bool)tg_dragEnabled.IsChecked; foreach (var item in tg_Area.VertexList) { - DragBehaviour.SetIsDragEnabled(item.Value, tg_dragEnabled.IsChecked != null && tg_dragEnabled.IsChecked.Value); + DragBehaviour.SetIsDragEnabled(item.Value, + tg_dragEnabled.IsChecked.Value); DragBehaviour.SetUpdateEdgesOnMove(item.Value, true); } } - private void tg_moveAnimation_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void MoveAnimationSelectionChanged(object sender, SelectionChangedEventArgs e) { switch ((MoveAnimation)tg_moveAnimation.SelectedItem) { @@ -189,47 +192,40 @@ private void tg_moveAnimation_SelectionChanged(object sender, SelectionChangedEv tg_Area.MoveAnimation = null; break; default: - tg_Area.MoveAnimation = AnimationFactory.CreateMoveAnimation((MoveAnimation)tg_moveAnimation.SelectedItem, TimeSpan.FromSeconds(1)); - tg_Area.MoveAnimation.Completed += MoveAnimation_Completed; + tg_Area.MoveAnimation = + AnimationFactory.CreateMoveAnimation((MoveAnimation)tg_moveAnimation.SelectedItem, + TimeSpan.FromSeconds(1)); + tg_Area.MoveAnimation!.Completed += MoveAnimation_Completed; break; } } - void MoveAnimation_Completed(object sender, EventArgs e) + private void MoveAnimation_Completed(object sender, EventArgs e) { tg_zoomctrl.ZoomToFill(); } - private void tg_deleteAnimation_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void DeleteAnimationSelectionChanged(object sender, SelectionChangedEventArgs e) { - switch ((DeleteAnimation)tg_deleteAnimation.SelectedItem) + tg_Area.DeleteAnimation = (DeleteAnimation)tg_deleteAnimation.SelectedItem switch { - case DeleteAnimation.None: - tg_Area.DeleteAnimation = null; - break; - case DeleteAnimation.Shrink: - tg_Area.DeleteAnimation = AnimationFactory.CreateDeleteAnimation((DeleteAnimation)tg_deleteAnimation.SelectedItem); - break; - default: - tg_Area.DeleteAnimation = AnimationFactory.CreateDeleteAnimation((DeleteAnimation)tg_deleteAnimation.SelectedItem); - break; - } + DeleteAnimation.None => null, + DeleteAnimation.Shrink => AnimationFactory.CreateDeleteAnimation( + (DeleteAnimation)tg_deleteAnimation.SelectedItem), + _ => AnimationFactory.CreateDeleteAnimation((DeleteAnimation)tg_deleteAnimation.SelectedItem) + }; } - private void tg_mouseoverAnimation_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void MouseOverAnimationSelectionChanged(object sender, SelectionChangedEventArgs e) { - switch ((MouseOverAnimation)tg_mouseoverAnimation.SelectedItem) + tg_Area.MouseOverAnimation = (MouseOverAnimation)tg_mouseoverAnimation.SelectedItem switch { - case MouseOverAnimation.None: - tg_Area.MouseOverAnimation = null; - break; - default: - tg_Area.MouseOverAnimation = AnimationFactory.CreateMouseOverAnimation((MouseOverAnimation)tg_mouseoverAnimation.SelectedItem); - break; - } + MouseOverAnimation.None => null, + _ => AnimationFactory.CreateMouseOverAnimation((MouseOverAnimation)tg_mouseoverAnimation.SelectedItem), + }; } - private void tg_highlightType_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void HighlightTypeSelectionChanged(object sender, SelectionChangedEventArgs e) { foreach (var item in tg_Area.VertexList) HighlightBehaviour.SetHighlightControl(item.Value, (GraphControlType)tg_highlightType.SelectedItem); @@ -237,15 +233,17 @@ private void tg_highlightType_SelectionChanged(object sender, SelectionChangedEv HighlightBehaviour.SetHighlightControl(item.Value, (GraphControlType)tg_highlightType.SelectedItem); } - private void tg_highlightEnabled_Checked(object sender, RoutedEventArgs e) + private void HighlightEnabledSelectionChanged(object sender, RoutedEventArgs e) { foreach (var item in tg_Area.VertexList) - HighlightBehaviour.SetIsHighlightEnabled(item.Value, tg_highlightEnabled.IsChecked != null && tg_highlightEnabled.IsChecked.Value); + HighlightBehaviour.SetIsHighlightEnabled(item.Value, + tg_highlightEnabled.IsChecked != null && tg_highlightEnabled.IsChecked.Value); foreach (var item in tg_Area.EdgesList) - HighlightBehaviour.SetIsHighlightEnabled(item.Value, tg_highlightEnabled.IsChecked != null && tg_highlightEnabled.IsChecked.Value); + HighlightBehaviour.SetIsHighlightEnabled(item.Value, + tg_highlightEnabled.IsChecked != null && tg_highlightEnabled.IsChecked.Value); } - private void tg_highlightEdgeType_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void HighlightEdgeTypeSelectionChanged(object sender, SelectionChangedEventArgs e) { foreach (var item in tg_Area.VertexList) HighlightBehaviour.SetHighlightEdges(item.Value, (EdgesType)tg_highlightEdgeType.SelectedItem); @@ -253,14 +251,5 @@ private void tg_highlightEdgeType_SelectionChanged(object sender, SelectionChang HighlightBehaviour.SetHighlightEdges(item.Value, (EdgesType)tg_highlightEdgeType.SelectedItem); } - #region INotifyPropertyChanged - public event PropertyChangedEventHandler PropertyChanged; - - private void OnPropertyChanged(string name) - { - if (PropertyChanged != null) - PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name)); - } - #endregion } -} +} \ No newline at end of file diff --git a/Examples/ShowcaseApp.WPF/Properties/Resources.resx b/Examples/ShowcaseApp.WPF/Properties/Resources.resx index b60e168..fa96c34 100644 --- a/Examples/ShowcaseApp.WPF/Properties/Resources.resx +++ b/Examples/ShowcaseApp.WPF/Properties/Resources.resx @@ -1,149 +1,163 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - ..\Templates\Mini\CommonMiniTemplate.xaml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - - + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + + ..\Templates\Mini\CommonMiniTemplate.xaml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089;utf-8 + + + In this example you can see how graph data filtering works. In GraphX you can assign many data filters in a queue that will be applied before graph layout calculation. Original graph remains intact in this case by default. When filtering is active each relayout method call will also refresh visual graph adding new visuals and removing old ones based on the data present in LogicCore.Graph. This approach allows filters to be applied dynamically and shows the results fast. - - ..\Pages\Mini\EdgesParallel.xaml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - - + + ..\Pages\Mini\EdgesParallel.xaml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089;utf-8 + + + In this example you can see how parallel edges can be handled and customized by GraphX. Edge labels also has special logic for parallel edges to be easily readable. Point mouse over the different settings to see tooltips. - + In this example you can see grouped graph at work. Play with different setting to see all the supported features. Point mouse over the different settings to see tooltips. - - ..\Pages\Mini\LayoutVCP.xaml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - - - ..\Templates\Mini\LayoutVCPTemplate.xaml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - - + + ..\Pages\Mini\LayoutVCP.xaml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089;utf-8 + + + + ..\Templates\Mini\LayoutVCPTemplate.xaml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089;utf-8 + + + In this example you can see how VCP (vertex connection points) works. Drag vertices to see VCP behavior in action and play with different settings on a settings panel to customize these behaviors. Point mouse over the different settings to see tooltips. diff --git a/Examples/ShowcaseApp.WPF/ShowcaseApp.WPF.csproj b/Examples/ShowcaseApp.WPF/ShowcaseApp.WPF.csproj index 11263fa..b7635bd 100644 --- a/Examples/ShowcaseApp.WPF/ShowcaseApp.WPF.csproj +++ b/Examples/ShowcaseApp.WPF/ShowcaseApp.WPF.csproj @@ -3,7 +3,7 @@ WinExe true - net8.0-windows + net9.0-windows latest true false @@ -16,7 +16,7 @@ - + diff --git a/Examples/ShowcaseApp.WPF/Templates/ERGraphXTemplates.xaml b/Examples/ShowcaseApp.WPF/Templates/ERGraphXTemplates.xaml index 2e7bac3..eefbc9d 100644 --- a/Examples/ShowcaseApp.WPF/Templates/ERGraphXTemplates.xaml +++ b/Examples/ShowcaseApp.WPF/Templates/ERGraphXTemplates.xaml @@ -2,8 +2,8 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:controls="https://westermo.com/graphx/" - xmlns:wpf="clr-namespace:ShowcaseApp.WPF"> - + xmlns:models="clr-namespace:ShowcaseApp.WPF.Models"> +