Skip to content

Instantly share code, notes, and snippets.

@ertugrulozcan
Created December 7, 2016 19:35
Show Gist options
  • Save ertugrulozcan/b384bb6992903db9b0aa2995c87c5f90 to your computer and use it in GitHub Desktop.
Save ertugrulozcan/b384bb6992903db9b0aa2995c87c5f90 to your computer and use it in GitHub Desktop.
using DevExpress.Xpf.Docking;
using Eigen.Infrastructure.Docking;
using Eigen.Infrastructure.Events;
using Eigen.Infrastructure.Events.Otc;
using Eigen.Infrastructure.Helpers;
using Eigen.Infrastructure.Services;
using Eigen.Infrastructure.Services.Docking;
using Eigen.Infrastructure.ViewModels;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Threading;
using Eigen.Infrastructure.Model;
using System.Windows.Input;
using Microsoft.Practices.ServiceLocation;
namespace Eigen.Infrastructure.RegionAdapters
{
public class DockingRegionAdapter : RegionAdapterBase<LayoutGroup>
{
#region Services
private readonly IEventAggregator eventAggregator;
private readonly IGuiRoutingService guiRoutingService;
private readonly IRegionManager regionManager;
private readonly IDockableRegionService dockRegSvc;
#endregion
#region Fields & Properties
public DockLayoutManager LayoutManager { get; private set; }
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="behaviorFactory"></param>
/// <param name="eventAggregator"></param>
public DockingRegionAdapter(IRegionBehaviorFactory behaviorFactory,
IEventAggregator eventAggregator,
IGuiRoutingService guiRoutingService,
IRegionManager regionManager,
IDockableRegionService dockRegSvc) : base(behaviorFactory)
{
this.eventAggregator = eventAggregator;
this.guiRoutingService = guiRoutingService;
this.regionManager = regionManager;
this.dockRegSvc = dockRegSvc;
this.eventAggregator.GetEvent<TraderLogoutEvent>().Subscribe(TraderLogoutEventHandler, ThreadOption.PublisherThread, true);
this.eventAggregator.GetEvent<TraderLoginEvent>().Subscribe(TraderLoginEventHandler, ThreadOption.PublisherThread, true);
this.eventAggregator.GetEvent<CloseCurrentWindowEvent>().Subscribe((e) => { this.OnCloseCurrentWindowHandling(e.ViewName, e.RegionName); });
this.eventAggregator.GetEvent<CloseApplicationNotificationEvent>().Subscribe(CloseApplicationEventHandler, ThreadOption.PublisherThread, true);
this.eventAggregator.GetEvent<RightMenuStatusChangedEvent>().Subscribe(RightMenuStatusChangedEventHandler, ThreadOption.PublisherThread, false);
//eventAggregator.GetEvent<CloseApplicationNotificationEvent>().Subscribe(CloseApplicationEventHandler, ThreadOption.PublisherThread, true);
}
#endregion
#region Methods
private void RecursiveClose(LayoutGroup layoutGroup, string regionName)
{
var mainRegion = regionManager.Regions[regionName];
for (int i = 0; i < layoutGroup.Items.Count; i++)
{
var layoutItem = layoutGroup.Items[i];
if (layoutItem is LayoutGroup)
RecursiveClose((LayoutGroup)layoutItem, regionName);
else if (layoutItem is LayoutPanel)
{
/*
var found = otcDockableSvc.WidgetList.ToList().Find((x => x.ViewName == layoutItem.Name));
otcDockableSvc.WidgetList.Remove(found);
*/
var view = (layoutItem as LayoutPanel).Content;
if (view != null)
mainRegion.Remove(view);
if (view is IDisposable)
{
(view as IDisposable).Dispose();
}
if (view is UserControl)
{
var dataContext = (view as UserControl).DataContext;
if (dataContext != null && dataContext is IDisposable)
{
(dataContext as IDisposable).Dispose();
}
}
}
}
layoutGroup.Items.Clear();
}
/// <summary>
/// Restore Workspace DockLayoutManager
/// Dosyadan okudugu config'e gore Docking Layout Manager'i restore eder.
/// </summary>
/// <param name="layoutManager"></param>
/// <param name="oldRegionName"></param>
public void RestoreWSDLM(Workspace workspace, DockLayoutManager layoutManager, string regionName)
{
var dockingConfigService = dockRegSvc.GetDockConfigService(regionName);
/*
LayoutTreeModel layoutTree = dockRegSvc.GetLayoutTree(regionName);
if (layoutTree == null)
{
layoutTree = this.ReadLayoutTree(dockingConfigService.GetUserConfigPath(regionName));
dockRegSvc.RegisterLayoutTree(regionName, layoutTree);
}
*/
//if (workspace.DockingLayoutTree == null)
// workspace.DockingLayoutTree = this.ReadLayoutTree(dockingConfigService.GetUserConfigPath(workspaceName));
workspace.DockingLayoutTree = dockingConfigService.RestoreLayout(layoutManager, workspace);
var dockService = dockRegSvc.GetDockService(regionName);
dockService.Restore();
this.FixLayoutProblems(layoutManager);
}
public void ClearRegionAndSave(WorkspaceChangingEvent e)
{
var layoutManager = dockRegSvc.GetLayoutManager(e.eventArgs.RegionName);
IRegion mainRegion = dockRegSvc.GetRegion(e.eventArgs.RegionName);
if (mainRegion != null && layoutManager != null)
{
var dockingConfigService = dockRegSvc.GetDockConfigService(e.eventArgs.RegionName);
dockingConfigService.SaveLayout(layoutManager, e.eventArgs.PreviousWorkspace);
if (layoutManager.FloatGroups != null)
{
foreach (var floatGroup in layoutManager.FloatGroups)
RecursiveClose(floatGroup, e.eventArgs.RegionName);
}
if (layoutManager.AutoHideGroups != null)
{
foreach (var hiddenGroup in layoutManager.AutoHideGroups)
RecursiveClose(hiddenGroup, e.eventArgs.RegionName);
}
this.RecursiveClose(layoutManager.LayoutRoot, e.eventArgs.RegionName);
var dockService = dockRegSvc.GetDockService(e.eventArgs.RegionName);
dockService.IsInitialized = false;
dockService.Save(-1, e.eventArgs.PreviousWorkspace);
//dockService.CurrentWS.WidgetList.Clear();
}
}
public void SaveWorkspaceLayout(Workspace workspace, string regionName)
{
var dockingConfigService = dockRegSvc.GetDockConfigService(regionName);
dockingConfigService.SaveLayout(workspace.DockingLayoutTree, workspace);
var dockService = dockRegSvc.GetDockService(regionName);
dockService.IsInitialized = false;
dockService.Save(-1, workspace);
/*
var layoutManager = dockRegSvc.GetLayoutManager(regionName);
IRegion mainRegion = dockRegSvc.GetRegion(regionName);
if (mainRegion != null && layoutManager != null)
{
var dockingConfigService = dockRegSvc.GetDockConfigService(regionName);
dockingConfigService.SaveLayout(layoutManager, workspace.Header);
var dockService = dockRegSvc.GetDockService(regionName);
dockService.IsInitialized = false;
dockService.Save(-1, workspace);
}
*/
}
public void ClearRegion(string regionName)
{
var layoutManager = dockRegSvc.GetLayoutManager(regionName);
IRegion mainRegion = dockRegSvc.GetRegion(regionName);
if (mainRegion != null && layoutManager != null)
{
var dockingConfigService = dockRegSvc.GetDockConfigService(regionName);
//dockingConfigService.SaveLayout(layoutManager);
if (layoutManager.FloatGroups != null)
{
foreach (var floatGroup in layoutManager.FloatGroups)
RecursiveClose(floatGroup, regionName);
}
if (layoutManager.AutoHideGroups != null)
{
foreach (var hiddenGroup in layoutManager.AutoHideGroups)
RecursiveClose(hiddenGroup, regionName);
}
this.RecursiveClose(layoutManager.LayoutRoot, regionName);
var dockService = dockRegSvc.GetDockService(regionName);
dockService.IsInitialized = false;
//dockService.Save();
//dockService.CurrentWS.WidgetList.Clear();
}
}
#endregion
#region Methods.AbstractImplementations
protected override void Adapt(IRegion region, LayoutGroup rootGroup)
{
this.LayoutManager = rootGroup.GetDockLayoutManager();
this.LayoutManager.DisposeOnWindowClosing = true;
this.LayoutManager.OwnsFloatWindows = true;
this.LayoutManager.ClosingBehavior = ClosingBehavior.ImmediatelyRemove;
this.LayoutManager.FloatingDocumentContainer = DevExpress.Xpf.Docking.Base.FloatingDocumentContainer.DocumentHost;
dockRegSvc.SetRegionDetials(region.Name, region, this.LayoutManager);
this.eventAggregator.GetEvent<DialogBoxOpeningEvent>().Subscribe(OnDialogBoxOpening);
this.eventAggregator.GetEvent<DialogBoxClosedEvent>().Subscribe(OnDialogBoxClosed);
//this.LayoutManager.ClosedPanelsBarVisibility = DevExpress.Xpf.Docking.Base.ClosedPanelsBarVisibility.Auto;
//this.LayoutManager.ClosedPanelsBarPosition = Dock.Bottom;
region.Views.CollectionChanged += (s, e) => OnViewsCollectionChanged(region, s, e);
}
protected override IRegion CreateRegion()
{
return new AllActiveRegion();
}
#endregion
#region Methods.CollectionsControl
void OnViewsCollectionChanged(IRegion region, object sender, NotifyCollectionChangedEventArgs e)
{
string baseViewName;
string moduleName;
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
{
try
{
List<UserControl> views = e.NewItems.Cast<UserControl>().ToList();
foreach (UserControl view in views)
{
GetViewAndModuleName(view, out baseViewName, out moduleName);
try
{
var dockSvc = dockRegSvc.GetDockService(region.Name);
var layoutManager = dockRegSvc.GetLayoutManager(region.Name);
DockableViewModelBase windowSet = dockSvc.CurrentWS.WidgetList.ToList().Find((item => item.ViewName == (string)region.Context));
// Eğer view layout ağacında bulunamazsa floatGroups ve autoHideGroups içerisinde aranır. Orada da yoksa yeni float panel olarak açılır.
LayoutPanel panel = this.GetLayoutPanel(windowSet.ViewName, layoutManager.LayoutRoot, layoutManager);
DockableViewModelBase vmb = view.DataContext as DockableViewModelBase;
if (panel == null)
{
var oldWindowSet = guiRoutingService.GetDefaultSettings(baseViewName);
Size floatSize = new Size(500, 500);
if (oldWindowSet != null)
floatSize = oldWindowSet.Size;
panel = layoutManager.DockController.AddPanel(this.GetLocationCenterPoint(floatSize), floatSize);
windowSet.Size = panel.FloatSize;
this.SetPanelOptions(panel, (string)region.Context, view, dockSvc.CloseWindowCommand);
this.SetPanelBindings(panel, vmb, windowSet);
vmb.OwnerDockingPanel = panel;
//vmb.SizeChanged += Vmb_SizeChanged;
//layoutManager.BringToFront(panel);
this.FixLayoutProblems(layoutManager);
// If layout is empty, dock to fill
if (!dockSvc.IsRestoring && layoutManager.LayoutRoot.Items.Count == 0)
{
layoutManager.DockController.Dock(panel, layoutManager.LayoutRoot, DevExpress.Xpf.Layout.Core.DockType.Fill);
}
else
{
vmb.SizeChanged += Vmb_SizeChanged;
layoutManager.BringToFront(panel);
}
}
else
{
this.SetPanelOptions(panel, (string)region.Context, view, dockSvc.CloseWindowCommand);
this.SetPanelBindings(panel, vmb, windowSet);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "");
}
}
}
catch { }
}
break;
case NotifyCollectionChangedAction.Remove:
{
}
break;
case NotifyCollectionChangedAction.Replace:
{
}
break;
case NotifyCollectionChangedAction.Move:
{
}
break;
case NotifyCollectionChangedAction.Reset:
{
}
break;
}
}
private void SetPanelOptions(LayoutPanel panel, string name, UserControl content, ICommand closeCommand)
{
panel.ClosingBehavior = ClosingBehavior.ImmediatelyRemove;
panel.CloseCommand = closeCommand;
panel.Content = content;
panel.AllowMaximize = false;
panel.ShowMaximizeButton = false;
panel.Name = name;
panel.MinWidth = 100;
panel.MinHeight = 100;
}
private void SetPanelBindings(LayoutPanel panel, DockableViewModelBase vmb, DockableViewModelBase windowSet)
{
Binding binding = new Binding();
vmb.ViewName = windowSet.ViewName;
vmb.BaseViewName = windowSet.BaseViewName;
vmb.Size = windowSet.Size;
binding = new Binding();
binding.Source = windowSet;
binding.Path = new PropertyPath(DockableViewModelBase.TargetNameProperty);
binding.Mode = BindingMode.TwoWay;
BindingOperations.SetBinding(vmb, DockableViewModelBase.TargetNameProperty, binding);
binding = new Binding();
binding.Source = windowSet;
binding.Path = new PropertyPath(DockableViewModelBase.QueryParamsProperty);
binding.Mode = BindingMode.TwoWay;
BindingOperations.SetBinding(vmb, DockableViewModelBase.QueryParamsProperty, binding);
binding = new Binding();
binding.Source = windowSet;
binding.Path = new PropertyPath(DockableViewModelBase.TitleProperty);
binding.Mode = BindingMode.TwoWay;
BindingOperations.SetBinding(vmb, DockableViewModelBase.TitleProperty, binding);
binding = new Binding();
binding.Source = vmb;
binding.Path = new PropertyPath(DockableViewModelBase.VisibleTitleProperty);
binding.Mode = BindingMode.TwoWay;
BindingOperations.SetBinding(panel, LayoutPanel.CaptionProperty, binding);
//binding = new Binding();
//binding.Source = vmb;
//binding.Path = new PropertyPath(DockableViewModelBase.SizeProperty);
//binding.Mode = BindingMode.TwoWay;
//System.Diagnostics.PresentationTraceSources.SetTraceLevel(panel, System.Diagnostics.PresentationTraceLevel.High);
//binding.Converter = new Infrastructure.Converter.DataBindingTestDebuggingConverter();
//BindingOperations.SetBinding(panel, LayoutPanel.FloatSizeProperty, binding);
//vmb.SizeChanged += (s2, e2) =>
//{
// System.Diagnostics.Debug.WriteLine(e2.PreviousSize + " >> " + e2.NewSize);
//};
}
private void Vmb_SizeChanged(object sender, Size oldSize, Size newSize)
{
var vmb = sender as DockableViewModelBase;
if (vmb.OwnerDockingPanel != null && vmb.OwnerDockingPanel.IsFloating && vmb.OwnerDockingPanel.Parent is FloatGroup)
{
var parenFloatGroup = vmb.OwnerDockingPanel.Parent as FloatGroup;
if (parenFloatGroup.FloatSize.Equals(newSize))
return;
parenFloatGroup.FloatSize = newSize;
parenFloatGroup.FloatLocation = this.GetLocationCenterPoint(newSize);
}
vmb.SizeChanged -= Vmb_SizeChanged;
}
private LayoutPanel GetLayoutPanel(string viewName, LayoutGroup group, DockLayoutManager layoutManager)
{
// LayoutGroups içerisinde ara;
LayoutPanel panel = this.SearchLayoutPanel(viewName, group);
if (panel != null)
return panel;
// FloutGroups içerisinde ara;
var floatGroups = layoutManager.FloatGroups;
foreach (var fGroup in floatGroups)
{
panel = this.SearchLayoutPanel(viewName, fGroup);
if (panel != null)
break;
}
if (panel != null)
return panel;
// AutoHideGroups içerisinde ara;
var autoHideGroups = layoutManager.AutoHideGroups;
foreach (var autoHideGroup in autoHideGroups)
{
panel = this.SearchLayoutPanel(viewName, autoHideGroup);
if (panel != null)
break;
}
if (panel != null)
return panel;
return null;
}
/// <summary>
/// Verilen grup içinde verilen viewName'e sahip paneli arar
/// Caption ile arama yapılır çünkü config'den okunan panellerde arama yapılır. Bu esnada Caption = UniqueViewModel'dir.
/// </summary>
/// <param name="viewName"></param>
/// <param name="group"></param>
/// <returns></returns>
private LayoutPanel SearchLayoutPanel(string viewName, LayoutGroup group)
{
foreach (var layoutItem in group.Items)
{
if (layoutItem is LayoutPanel)
{
if ((layoutItem as LayoutPanel).Tag == null)
(layoutItem as LayoutPanel).Tag = string.Empty;
if ((layoutItem as LayoutPanel).Tag.ToString() == viewName)
return layoutItem as LayoutPanel;
}
else if (layoutItem is LayoutGroup)
{
LayoutPanel panel = this.SearchLayoutPanel(viewName, layoutItem as LayoutGroup);
if (panel != null)
return panel;
}
}
return null;
}
private LayoutPanel SearchLayoutPanelByViewName(string viewName, LayoutGroup group)
{
foreach (var layoutItem in group.Items)
{
if (layoutItem is LayoutPanel)
{
var view = (layoutItem as LayoutPanel).Content;
if (view != null)
{
var dataCon = (view as UserControl).DataContext;
if (dataCon != null && dataCon is DockableViewModelBase)
{
if ((dataCon as DockableViewModelBase).ViewName == viewName)
return layoutItem as LayoutPanel;
}
}
}
else if (layoutItem is LayoutGroup)
{
LayoutPanel panel = this.SearchLayoutPanelByViewName(viewName, layoutItem as LayoutGroup);
if (panel != null)
return panel;
}
}
return null;
}
private static void GetViewAndModuleName(UserControl uc, out string viewName, out string moduleName)
{
viewName = uc.GetType().ToString();
string[] classParts = viewName.Split('.');
viewName = classParts[classParts.Length - 1];
moduleName = classParts[classParts.Length - 3];
}
#endregion
#region Event Handler Methods
private void OnCloseCurrentWindowHandling(string viewName, string regionName)
{
var layoutManager = dockRegSvc.GetLayoutManager(regionName);
for (int i = 0; i < layoutManager.FloatGroups.Count; i++)
{
var panel = SearchLayoutPanelByViewName(viewName, layoutManager.FloatGroups[i]);
if (panel != null)
{
layoutManager.DockController.Close(panel);
i--;
}
}
dockRegSvc.RemoveView(viewName, regionName);
}
private void CloseApplicationEventHandler(int obj)
{
UIHelper.UiInvoke(DispatcherPriority.Background, true,
(Action)(() =>
{
// Docking layout save when closing
//ClearRegionAndSave(RegionNames.MainWSRegion);
}));
}
private void RightMenuStatusChangedEventHandler(RightMenuStatusChangedEvent obj)
{
if (obj.IsClosing)
{
this.NormalizeAllFloatingPanels();
}
else
{
this.MinimizeAllFloatingPanels();
}
}
private void MinimizeAllFloatingPanels()
{
var layoutManager = dockRegSvc.GetLayoutManager(RegionNames.MainWSRegion);
if (layoutManager.FloatGroups != null)
{
foreach (var floatGroup in layoutManager.FloatGroups)
floatGroup.FloatState = FloatState.Minimized;
}
}
private void NormalizeAllFloatingPanels()
{
var layoutManager = dockRegSvc.GetLayoutManager(RegionNames.MainWSRegion);
if (layoutManager.FloatGroups != null)
{
foreach (var floatGroup in layoutManager.FloatGroups)
floatGroup.FloatState = FloatState.Normal;
}
}
private void TraderLoginEventHandler(TraderLoginEvent obj)
{
//UIHelper.UiInvoke(DispatcherPriority.Background, true,
// (Action)(() =>
// {
// var regionName = RegionNames.OtcMainRegion;
// var layoutManager = dockRegSvc.GetLayoutManager(regionName);
// if (obj.IsLoggedIn && layoutManager != null)
// {
// this.RestoreWSDLM(dockRegSvc.GetDockService(regionName).CurrentWS, layoutManager, regionName);
// }
// }));
}
private void TraderLogoutEventHandler(TraderLogoutEvent obj)
{
//ClearRegionAndSave(RegionNames.OtcMainRegion);
}
/// <summary>
///
/// </summary>
/// <param name="configFilePath"></param>
/// <returns></returns>
private LayoutTreeModel ReadLayoutTree(string configFilePath)
{
try
{
if (System.IO.File.Exists(configFilePath))
{
string treeAsJson = System.IO.File.ReadAllText(configFilePath);
LayoutTreeModel layoutTree = Newtonsoft.Json.JsonConvert.DeserializeObject<LayoutTreeModel>(treeAsJson);
return layoutTree;
}
else
return null;
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message);
return null;
}
}
private void OtcModuleCloseEventHandler(string obj)
{
//some day might be useful
}
private Point GetLocationCenterPoint(Size panelSize)
{
double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
double windowWidth = Application.Current.MainWindow.ActualWidth;
if (windowWidth < 100)
windowWidth = screenWidth;
double windowHeight = Application.Current.MainWindow.ActualHeight;
if (windowHeight < 100)
windowHeight = screenHeight;
if (windowWidth <= 0 || windowWidth > screenWidth)
windowWidth = screenWidth;
if (windowHeight <= 0 || windowHeight > screenHeight)
windowHeight = screenHeight;
return new Point((windowWidth - panelSize.Width) / 2, (windowHeight - panelSize.Height) / 2 - 100);
}
private void FixLayoutProblems(DockLayoutManager layoutManager)
{
this.RemoveUnsettedPanels(layoutManager.LayoutRoot);
var floatGroups = layoutManager.FloatGroups;
foreach (var fGroup in floatGroups)
this.RemoveUnsettedPanels(fGroup);
var autoHideGroups = layoutManager.AutoHideGroups;
foreach (var autoHideGroup in autoHideGroups)
this.RemoveUnsettedPanels(autoHideGroup);
}
/// <summary>
/// Content'i set edilememiş panel var mı?
/// Varsa paneli docking layout tree'den kaldırır.
/// </summary>
/// <returns></returns>
private void RemoveUnsettedPanels(BaseLayoutItem layoutItem)
{
if (layoutItem is LayoutPanel)
{
LayoutPanel panel = (layoutItem as LayoutPanel);
if (panel.Content == null)
{
panel.Parent.Remove(panel);
}
}
else if (layoutItem is LayoutGroup)
{
LayoutGroup group = (layoutItem as LayoutGroup);
for (int i = 0; i < group.Items.Count; i++)
this.RemoveUnsettedPanels(group.Items[i]);
}
}
#endregion
#region DialogBox Settings
private bool isDialogBoxOpened;
private List<FloatGroup> MinimizedFloatGroupList = new List<FloatGroup>();
private void OnDialogBoxOpening(DialogBoxOpeningEvent obj)
{
var workspaceManager = ServiceLocator.Current.GetInstance<IWorkspaceManagementService>();
if (workspaceManager.IsWorkspaceChanging)
return;
if (this.LayoutManager != null)
{
for (int i = 0; i < this.LayoutManager.FloatGroups.Count; i++)
{
UIHelper.UiInvoke(DispatcherPriority.ContextIdle, false, delegate
{
FloatGroup fGroup = this.LayoutManager.FloatGroups[i];
if (!fGroup.IsClosed)
{
this.MinimizedFloatGroupList.Add(fGroup);
fGroup.FloatState = FloatState.Minimized;
}
});
}
}
this.isDialogBoxOpened = true;
}
private void OnDialogBoxClosed(DialogBoxClosedEvent obj)
{
this.isDialogBoxOpened = false;
var workspaceManager = ServiceLocator.Current.GetInstance<IWorkspaceManagementService>();
if (workspaceManager.IsWorkspaceChanging)
{
this.MinimizedFloatGroupList.Clear();
return;
}
if (this.LayoutManager != null)
{
foreach (var fGroup in this.MinimizedFloatGroupList)
{
if (!fGroup.IsClosed)
{
fGroup.FloatState = FloatState.Normal;
}
}
this.MinimizedFloatGroupList.Clear();
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Eigen.Infrastructure.Events
{
public interface IDialogEvent
{
string Error { get; }
}
}
using System.Collections.Generic;
using System.Threading;
using System.Windows.Input;
using Eigen.Infrastructure.Events;
using Eigen.Infrastructure.Views;
using Microsoft.Practices.Prism.Events;
using WpfDialogManagement;
using WpfDialogManagement.Contracts;
using Microsoft.Practices.ServiceLocation;
using System;
using System.Windows.Controls;
using WpfDialogManagement.Manager;
using Eigen.Infrastructure.ViewModels;
using Microsoft.Practices.Prism.Regions;
namespace Eigen.Infrastructure.Services
{
public class WpfUIWindowDialogService : IUIWindowDialogService
{
private readonly IEventAggregator eventAggregator;
private readonly IDialogManager _dialogManager;
private Dictionary<string, IDialog> openDialogs { get; set; }
//usage
//eventAggregator.GetEvent<OpenDialogEvent>().Publish(new OpenDialogEvent("Hata oluştu", "Hataların en kötüsü", DialogMode.OkCancel, DialogWindowType.Message));
public WpfUIWindowDialogService(IDialogManager dialogManager, IEventAggregator eventAggregator)
{
this._dialogManager = dialogManager;
this.eventAggregator = eventAggregator;
this.openDialogs = new Dictionary<string, IDialog>();
this.eventAggregator.GetEvent<OpenDialogEvent>().Subscribe(OpenDialogEventHandler, ThreadOption.PublisherThread, true);
this.eventAggregator.GetEvent<CloseDialogEvent>().Subscribe(CloseDialogEventHandler, ThreadOption.PublisherThread, true);
}
#region OpenDialogEvent
// N'aptık?
// Burada olay şu; Eğer OpenDialogEvent veya CloseDialog fire edilmek istendiğinde Workspace değişim prosesi devam etmekte ise minimized edilmiş floating paneller sıkıntı çıkartabiliyor.
// Bu nedenle IsWorkspaceChanging ise ShowMessageDialog veya CloseDialog metodu Workspace değiştikten sonra çağrılır. Ardından unsubscribe edilir.
// Eğer IsWorkspaceChanging false ise zaten direkt çağrılır.
private IDialogEvent CurrentDialogEventObject = null;
private void OpenDialogEventHandler(OpenDialogEvent e)
{
IWorkspaceManagementService workspaceManager = ServiceLocator.Current.GetInstance<IWorkspaceManagementService>();
if (workspaceManager.IsWorkspaceChanging)
{
this.CurrentDialogEventObject = e;
workspaceManager.OnWorkspaceChanged += WorkspaceManager_OnWorkspaceChanged;
}
else
{
this.ShowMessageDialog(e);
}
}
private void WorkspaceManager_OnWorkspaceChanged(object sender, WorkspaceChangedEventArgs e)
{
IWorkspaceManagementService workspaceManager = ServiceLocator.Current.GetInstance<IWorkspaceManagementService>();
if (this.CurrentDialogEventObject != null)
{
if (this.CurrentDialogEventObject is OpenDialogEvent)
this.ShowMessageDialog(this.CurrentDialogEventObject as OpenDialogEvent);
else if (this.CurrentDialogEventObject is CloseDialogEvent)
this.CloseDialog(this.CurrentDialogEventObject.Error);
workspaceManager.OnWorkspaceChanged -= WorkspaceManager_OnWorkspaceChanged;
this.CurrentDialogEventObject = null;
}
}
private void CloseDialogEventHandler(CloseDialogEvent e)
{
IWorkspaceManagementService workspaceManager = ServiceLocator.Current.GetInstance<IWorkspaceManagementService>();
if (workspaceManager.IsWorkspaceChanging)
{
this.CurrentDialogEventObject = e;
workspaceManager.OnWorkspaceChanged += WorkspaceManager_OnWorkspaceChanged;
}
else
{
this.CloseDialog(e.Error);
}
}
#endregion
#region Methods
private void ShowMessageDialog(OpenDialogEvent obj)
{
// if the window is already open
if (openDialogs.ContainsKey(obj.Error))
{
if (obj.AlreadyOpenedCallback != null)
obj.AlreadyOpenedCallback.Invoke();
return;
}
this.eventAggregator.GetEvent<DialogBoxOpeningEvent>().Publish(new DialogBoxOpeningEvent());
switch (obj.dWinType)
{
case DialogWindowType.Message:
{
IDialog dialog;
var messError = Localization.LocalizationUtility.Convert(obj.Error);
var messTitle = Localization.LocalizationUtility.Convert(obj.title);
dialog = _dialogManager.CreateMessageDialog(messError, messTitle, obj.mode);
ConvertDialogTexts(dialog);
openDialogs.Add(obj.Error, dialog);
dialog.Ok = dialog.Cancel = () =>
{
CloseDialog(obj.Error);
};
dialog.Yes = obj.YesAction;
dialog.No = obj.NoAction;
dialog.Show();
}
break;
case DialogWindowType.Progress:
{
IProgressDialog dialogPr;
dialogPr = _dialogManager.CreateProgressDialog(obj.Error, obj.title, obj.mode);
ConvertDialogTexts(dialogPr);
openDialogs.Add(obj.Error, dialogPr);
// We do some asynchronous work for 2 secs...
dialogPr.Show(() =>
{
for (var i = 0; i < 10; i++)
{
Thread.Sleep(200);
dialogPr.Progress += 10;
}
});
}
break;
case DialogWindowType.CustomOkCancelControl:
{
IDialog customOkCancelDialog;
var custWin1 = (UserControl)ServiceLocator.Current.GetInstance(obj.viewType);
ICustomOkCancelControl custWin = null;
if (custWin1.DataContext is ICustomOkCancelControl)
{
custWin = (ICustomOkCancelControl)custWin1.DataContext;
custWin.CustControlNavParams = obj.NavParams;
}
customOkCancelDialog = _dialogManager.CreateCustomContentDialog(custWin1, obj.title, DialogMode.OkCancel);
ConvertDialogTexts(customOkCancelDialog);
openDialogs.Add(obj.Error, customOkCancelDialog);
customOkCancelDialog.CloseBehavior = DialogCloseBehavior.ExplicitClose;
customOkCancelDialog.Ok = () =>
{
bool isOk = true;
if (custWin != null)
isOk = custWin.OkClicked();
if (isOk && obj.OkAction != null)
{
obj.OkAction();
}
if (isOk)
CloseDialog(obj.Error);
};
customOkCancelDialog.Cancel = () =>
{
bool isOk = true;
if (custWin != null)
isOk = custWin.CancelClicked();
if (isOk && obj.CancelAction != null)
{
obj.CancelAction();
}
if (isOk)
CloseDialog(obj.Error);
};
customOkCancelDialog.Show();
}
break;
case DialogWindowType.ModalWindow:
{
IDialog customOkCancelDialog;
var custWin1 = (UserControl)ServiceLocator.Current.GetInstance(obj.viewType);
customOkCancelDialog = _dialogManager.CreateCustomContentDialog(custWin1, obj.title, DialogMode.Cancel);
ConvertDialogTexts(customOkCancelDialog);
openDialogs.Add(obj.Error, customOkCancelDialog);
customOkCancelDialog.CloseBehavior = DialogCloseBehavior.ExplicitClose;
customOkCancelDialog.Cancel = () =>
{
CloseDialog(obj.Error);
};
customOkCancelDialog.Show();
}
break;
default:
{
IMessageDialog messDialog;
var error = Localization.LocalizationUtility.Convert(obj.Error);
var title = Localization.LocalizationUtility.Convert(obj.title);
messDialog = _dialogManager.CreateMessageDialog(error, title, obj.mode);
ConvertDialogTexts(messDialog);
openDialogs.Add(obj.Error, messDialog);
messDialog.Ok = messDialog.Cancel = () =>
{
CloseDialog(obj.Error);
};
messDialog.Show();
}
break;
}
}
private void CloseDialog(string error)
{
if (openDialogs.ContainsKey(error))
{
var dialog = openDialogs[error];
if (dialog is ICustomContentDialog)
{
var userControl = (((ICustomContentDialog)dialog).Content) as UserControl;
if (userControl is IDisposable)
(userControl as IDisposable).Dispose();
if (userControl.DataContext is IDisposable)
(userControl.DataContext as IDisposable).Dispose();
}
dialog.Close();
openDialogs.Remove(error);
this.eventAggregator.GetEvent<DialogBoxClosedEvent>().Publish(new DialogBoxClosedEvent());
}
}
public void SetOkButtonEnabled(string dialogName, bool isEnabled)
{
if (openDialogs != null && openDialogs.ContainsKey(dialogName))
openDialogs[dialogName].CanOk = isEnabled;
}
private void ConvertDialogTexts(IDialog dialog)
{
dialog.OkText = Localization.LocalizationUtility.Convert("Ok");
dialog.CancelText = Localization.LocalizationUtility.Convert("Cancel");
dialog.YesText = Localization.LocalizationUtility.Convert("Yes");
dialog.NoText = Localization.LocalizationUtility.Convert("No");
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment