Imports System.ComponentModel
Imports DevExpress.Xpf.Editors
Imports System.Data.Objects
Imports System.Data.Objects.DataClasses
Imports System.Data.Metadata.Edm
Imports System.Data
Imports System.Collections.Specialized
Imports tsl5
Imports DevExpress.Xpf.Core
Imports DevExpress.Xpf.Core.Native
Imports DevExpress.Xpf.Grid
Imports System.Data.EntityClient
Imports System.Data.Common
Imports DevExpress.Xpf.Docking
'Imports System.Data.Entity.Core.Objects
'Imports System.Data.Entity.Infrastructure
Imports DevExpress.Mvvm
Imports DevExpress.Xpf.Editors.Settings
Imports DevExpress.Xpf.Printing
Imports tsWPF.Controles
Imports System.Threading.Tasks

Public Interface IApLineas
    'Function ConfiguraApLineas(dcfg As Datos.DatosConfiguracionCliente, dcn As Datos.DatosConexionCliente, dsc As Datos.DatosSesionCliente, OtrosParametros As String) As ApLineas
    Function ObtieneRejilla() As tsGridControl
    ReadOnly Property Titulo As String
    '  ReadOnly Property CampoIndice As String   
    ReadOnly Property NombreTablaBase As String
    Function ObtieneContexto(dcn As tsl5.Datos.DatosConexionCliente) As System.Data.Objects.ObjectContext
    Function ObtieneCampoIndice() As String
    Sub EstableceDataContext(ByRef DataContext As Object, Optional Background As Boolean = False)
    Sub EstableceApLin(ApLin As ApLineas)
    ' Sub Editar(Celda As EditGridCellData, Defecto As Boolean)
    Sub Nuevo()
    Function ObtienePermisos() As Permisos


End Interface
<TypeConverterAttribute(GetType(System.ComponentModel.ExpandableObjectConverter))>
Public Class ApLineas
    ' Public WithEvents dm As DockLayoutManager
    '    Public Shared WithEvents tv As TableView
    Public dcfg As Datos.DatosConfiguracionCliente
    Public dcn As Datos.DatosConexionCliente
    Public dsc As Datos.DatosSesionCliente
    Public OtrosParametros As String
    Public Titulo As String
    Public CampoIndice As String
    Friend DatosCambiados As Boolean
    Public uc As UserControl
    Public Rejilla As tsGridControl
    Public IApLin As IApLineas
    Public WithEvents Contexto As System.Data.Objects.ObjectContext
    Public Property Refrescar As Boolean = True
    Public PermisosConcedidos As Permisos
    Public Event Cargado()

    Event Enlazar(Celda As EditGridCellData, Defecto As Boolean)

    Event ImprimirPlantilla(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs, idPlantilla As Integer)

    Event EjecutarAccion(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs, idAccion As Integer)

    Event SeleccionMultipleHabilitadoCambiado(Habilitar As Boolean)

    Event InvertirSeleccion()

    Event ValidarSeleccionar()

    Public Event AntesMensajeEliminar(ByRef Cancelar As Boolean, ByRef EliminacionCorrecta As Boolean)
    Public Event AntesEliminar(Fila As Object, ByRef Cancelar As Boolean)

    ' Public Property ErroresValidacion As ErroresValidacion
    ' Public Recargando As Boolean = False

    Property ContenedorL As ContenedorLineas
    'Private selectionHelper As New SelectionHelper(Of Guid)()
    Public ElementosSeleccionados As New SelectionHelper(Of Integer)


    Public GrupoDocumentos As DocumentGroup
    Public DocPanel As DevExpress.Xpf.Docking.DocumentPanel

    Public Property RefrescoSolicitado As Boolean = False
    Public Property DeshabilitarRefresco As Boolean = False
    Public Property DeshabilitarRefrescarOtrasPestañas = False
    Public Delegate Sub Ayuda(Codigo As String)
    '    Public Delegate Function Diseño(bd As ObjectContext, Operacion As OperacionDiseñoEnum, apl As ApLineas, ByRef Descripcion As String, ByRef TodosUsuarios As Boolean, DiseñoRejillas As Byte()) As Byte()
    Public Delegate Sub ErrorNoControlado(Aplicacion As ApLineas, ex As Exception)
    Public Delegate Sub DelegadoCargado(Aplicacion As ApLineas)
    Friend Property DelegadoAyuda As Ayuda
    Friend Property DelegadoDiseño As ApCabLin.Diseño
    Friend Property DelegadoErrorNoControlado As ErrorNoControlado
    Friend Property dlgCargado As DelegadoCargado
    Friend DiseñoOriginal As Byte()
    Friend Property AperturaAutomatica As Boolean
    Private DiseñoCargado As Boolean
    Public ApCargado As Boolean



    '  Public Event Cargado()
    'Public Event Editar(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)
    'Public Event Nuevo(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)

    'Sub LanzaEventoCargado()
    '    RaiseEvent Cargado()
    'End Sub
    'Sub LanzaEditar(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)
    '    RaiseEvent Editar(sender, e)
    'End Sub

    Public Overloads Shared Sub AbrirUcL(uc As IApLineas, DocumentGroup As DocumentGroup, dcfg As Datos.DatosConfiguracionCliente, dcn As Datos.DatosConexionCliente, dsc As Datos.DatosSesionCliente, OtrosParametros As String, Optional EditarEnDobleClick As Boolean = True, Optional FuncionAyuda As Ayuda = Nothing, Optional FuncionDiseño As ApCabLin.Diseño = Nothing, Optional FuncionErrorNoControlado As ErrorNoControlado = Nothing, Optional FuncionCargado As DelegadoCargado = Nothing)
        AbrirUcL(uc, DocumentGroup, dcfg, dcn, 0, dsc, OtrosParametros, EditarEnDobleClick, FuncionAyuda, FuncionDiseño, FuncionErrorNoControlado, FuncionCargado)
    End Sub
    Public Overloads Shared Sub AbrirUcL(uc As IApLineas, DocumentGroup As DocumentGroup, dcfg As Datos.DatosConfiguracionCliente, dcn As Datos.DatosConexionCliente, NumeroBD As Integer, dsc As Datos.DatosSesionCliente, OtrosParametros As String, Optional EditarEnDobleClick As Boolean = True, Optional FuncionAyuda As Ayuda = Nothing, Optional FuncionDiseño As ApCabLin.Diseño = Nothing, Optional FuncionErrorNoControlado As ErrorNoControlado = Nothing, Optional FuncionCargado As DelegadoCargado = Nothing)

        Dim apl As ApLineas
        Try


            Dim bNuevoPanel As Boolean = True

            apl = New tsWPF.ApLineas(uc, uc, dcfg, dcn, dsc, OtrosParametros)
            Dim usctrl = DirectCast(uc, UserControl)

            Dim docpanel As DevExpress.Xpf.Docking.DocumentPanel


            Dim dc = (From p In DocumentGroup.Items Where p.Tag = OtrosParametros)
            If dc.Count > 0 Then
                docpanel = dc.First
                bNuevoPanel = False
            Else
                If tsWPF.Configuracion.MostrarBotonCerrarEnPestaña Then DocumentGroup.ClosePageButtonShowMode = ClosePageButtonShowMode.InAllTabPageHeaders
                If Not DXSplashScreen.IsActive Then
                    DXSplashScreen.Show(Of SplashScreenTecnosis)()
                    DXSplashScreen.SetState("Cargando ...")
                End If
                docpanel = New DevExpress.Xpf.Docking.DocumentPanel
                'docpanel.Tag = apl.uc.GetType.Name 
                docpanel.Tag = OtrosParametros
            End If

            uc.EstableceApLin(apl)
            apl.Titulo = apl.IApLin.Titulo
            apl.GrupoDocumentos = DocumentGroup

            apl.Contexto = uc.ObtieneContexto(dcn)
            If apl.Contexto IsNot Nothing AndAlso apl.Contexto.Connection.State = ConnectionState.Closed Then apl.AperturaAutomatica = True
            apl.CampoIndice = uc.ObtieneCampoIndice
            apl.DocPanel = docpanel
            apl.PermisosConcedidos = uc.ObtienePermisos
            If Not apl.PermisosConcedidos.Consultar Then Throw New Exception("No tiene permiso para abrir esta aplicación (" & uc.Titulo & ")")
            apl.Rejilla = uc.ObtieneRejilla
            apl.Rejilla.PropiedadesTSGC.PermisosDefecto = apl.PermisosConcedidos
            Dim tv As TableView = apl.Rejilla.View

            apl.Rejilla.View.ShowSearchPanelCloseButton = False
            apl.Rejilla = uc.ObtieneRejilla
            apl.Rejilla.View.AllowEditing = True
            apl.Rejilla.View.SearchPanelFindMode = FindMode.Always

            apl.Rejilla.View.ShowSearchPanel(True)

            For Each c In apl.Rejilla.Columns
                'c.AllowEditing = DevExpress.Utils.DefaultBoolean.False
                If c.CellTemplate Is Nothing Then
                    c.ReadOnly = True
                Else
                    c.AllowEditing = DevExpress.Utils.DefaultBoolean.False
                End If
            Next


            Dim es As New CheckEditSettings
            es.IsThreeState = False

            Dim dt As New DataTemplate
            dt.VisualTree = New FrameworkElementFactory(GetType(CheckEdit))
            dt.VisualTree.SetBinding(CheckEdit.IsCheckedProperty, New Binding("Data.tswpf_seleccionar"))
            dt.VisualTree.SetValue(CheckEdit.HorizontalAlignmentProperty, HorizontalAlignment.Center)

            If Not apl.Rejilla.Columns.Any(Function(x) x.FieldName = "tswpf_seleccionar") Then
                Dim gcseleccionar As New GridColumn With {
                    .FieldName = "tswpf_seleccionar",
                    .UnboundType = DevExpress.Data.UnboundColumnType.Boolean,
                    .Width = 80,
                    .IsSmart = True,
                    .Visible = False,
                    .VisibleIndex = 0,
                    .EditSettings = es,
                    .AllowEditing = DevExpress.Utils.DefaultBoolean.True,
                    .Header = "Seleccionar",
                    .HorizontalHeaderContentAlignment = HorizontalAlignment.Center,
                    .CellTemplate = dt
                    }
                apl.Rejilla.Columns.Insert(0, gcseleccionar)
            End If

            AddHandler apl.Rejilla.CustomUnboundColumnData, AddressOf apl.CustomUnboudColumnData

            If EditarEnDobleClick Then AddHandler apl.Rejilla.MouseDoubleClick, AddressOf apl.RejillaDobleClick
            Dim ap As New tsWPF.ContenedorLineas(apl, uc)
            ap.btNuevo.IsEnabled = apl.PermisosConcedidos.Nuevos
            ap.btEliminar.IsEnabled = False 'apl.PermisosConcedidos.Eliminar and ElementosSeleccionados.GetSelectionCount >0 and apl.ContenedorL.btSeleccionar.IsChecked=True 



            If bNuevoPanel Then
                apl.DelegadoAyuda = FuncionAyuda
                apl.DelegadoDiseño = FuncionDiseño
                apl.DelegadoErrorNoControlado = FuncionErrorNoControlado
                apl.dlgCargado = FuncionCargado
                docpanel.Caption = uc.Titulo
                docpanel.Content = ap
                docpanel.ClosingBehavior = DevExpress.Xpf.Docking.ClosingBehavior.ImmediatelyRemove
                DocumentGroup.Items.Add(docpanel)
                If Comun.dm Is Nothing Then Comun.dm = DocumentGroup.GetDockLayoutManager
                apl.ContenedorL.btAyuda.IsVisible = (Not FuncionAyuda Is Nothing)
                apl.ContenedorL.MenuDiseño.IsVisible = (Not FuncionDiseño Is Nothing)
                apl.ContenedorL.MenuExportar.IsEnabled = apl.PermisosConcedidos.Exportar
                'Try
                '    If apl.DelegadoDiseño IsNot Nothing Then
                '        Try
                '            Dim b As Byte() = Nothing

                '            b = apl.DelegadoDiseño.Invoke(apl.Contexto, OperacionDiseñoEnum.ABRIR, apl.uc.GetType.ToString, "", True, Nothing)
                '            If b IsNot Nothing Then
                '                apl.DiseñoOriginal = apl.ContenedorL.ObtieneDiseñoActual
                '                Dim ld As New DiseñoRejillas
                '                ld = tsl5.Utilidades.deserializar(System.Text.Encoding.Unicode.GetString(b), ld.GetType)
                '                Dim i As Integer
                '                Dim lg As List(Of tsGridControl) = Nothing
                '                tsWPF.ObtieneHijosDeTipo(Of tsGridControl)(ap.contenido, lg)
                '                For Each l In lg
                '                    i += 1
                '                    If l.Name = "" Then l.Name = "tsRejilla-" & i.ToString
                '                    Try
                '                        If ld.Rejillas.Any(Function(x) x.Nombre = l.Name) Then
                '                            Dim dr As DiseñoRejilla = ld.Rejillas.Where(Function(x) x.Nombre = l.Name).First
                '                            l.RestoreLayoutFromStream(New System.IO.MemoryStream(dr.Diseño))
                '                        End If
                '                    Catch ex As Exception
                '                        If apl.DelegadoErrorNoControlado IsNot Nothing Then apl.DelegadoErrorNoControlado.Invoke(apl, ex)
                '                        DXMessageBox.Show(ex.Message, "Error btDiseño_Itemclick")
                '                        'Debug.Write("Error DelegadoDiseño Rejilla")
                '                    End Try
                '                Next
                '                '  Dim drs = System.Text.Encoding.Unicode.GetBytes(tsl5.Utilidades.serializar(ld))
                '            End If
                '        Catch ex As Exception
                '            If apl.DelegadoErrorNoControlado IsNot Nothing Then apl.DelegadoErrorNoControlado.Invoke(apl, ex)

                '            DXMessageBox.Show(ex.Message, "Error AbrirUclL - Diseño")
                '            'Debug.Write("Error DelegadoDiseño AbrirUCCL")
                '        End Try
                '    End If
                'Catch ex As Exception
                '    If apl.DelegadoErrorNoControlado IsNot Nothing Then apl.DelegadoErrorNoControlado.Invoke(apl, ex)
                '    DXMessageBox.Show(ex.Message, "Error AbrirUclL - Diseño")
                'End Try
            End If
            Comun.dm.DockController.Activate(docpanel)
        Catch ex As Exception
            If DXSplashScreen.IsActive Then DXSplashScreen.Close()
            DXMessageBox.Show(ex.Message, "Atención", MessageBoxButton.OK, MessageBoxImage.Exclamation)
            If FuncionErrorNoControlado IsNot Nothing Then FuncionErrorNoControlado.Invoke(apl, ex)
        End Try

    End Sub


    'Sub LanzaEventoCargado()
    '    RaiseEvent Cargado()
    'End Sub

    'Sub LanzaNuevo(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)
    '    RaiseEvent Nuevo(sender, e)
    'End Sub

    Private Sub RejillaDobleClick(sender As Object, e As MouseButtonEventArgs)
        Try
            RaiseEvent Enlazar(Nothing, True)
        Catch ex As Exception
        End Try
    End Sub

    Public Sub New(IApLIN As IApLineas, UC As UserControl, dcfg As tsl5.Datos.DatosConfiguracionCliente, dcn As tsl5.Datos.DatosConexionCliente, dsc As tsl5.Datos.DatosSesionCliente, OtrosParametros As String)
        Me.uc = UC
        Me.IApLin = IApLIN
        Me.dcfg = dcfg
        Me.dcn = dcn
        Me.dsc = dsc
        Me.OtrosParametros = OtrosParametros
        '    Me.Contexto = IApLIN.ObtieneContexto(dcn)
        AddHandler UC.PreviewKeyDown, AddressOf ApLin_PreviewKeyDown
        AddHandler UC.Loaded, AddressOf usctrl_Cargado


        'Me.IApLin.ObtieneRejilla.DelegadoComando = New DelegateCommand(Of Object)(AddressOf Seleccionar)        
    End Sub

    Private Sub usctrl_Cargado(sender As Object, e As RoutedEventArgs)
        Try
            If Me.DelegadoDiseño IsNot Nothing And Not DiseñoCargado Then
                Try
                    DiseñoCargado = True
                    Dim b As Byte() = Nothing
                    Me.DiseñoOriginal = Me.ContenedorL.ObtieneDiseñoActual
                    b = Me.DelegadoDiseño.Invoke(Me.Contexto, OperacionDiseñoEnum.ABRIR, Me.uc.GetType.ToString, "", True, Nothing)
                    If b IsNot Nothing Then
                        Dim ld As New DiseñoRejillas
                        ld = tsl5.Utilidades.deserializar(System.Text.Encoding.Unicode.GetString(b), ld.GetType)
                        Dim i As Integer
                        Dim lg As List(Of tsGridControl) = Nothing
                        tsWPF.ObtieneHijosDeTipo(Of tsGridControl)(sender, lg)
                        For Each l In lg
                            i += 1
                            If l.Name = "" Then l.Name = "tsRejilla-" & i.ToString
                            Try
                                If ld.Rejillas.Any(Function(x) x.Nombre = l.Name) Then
                                    Dim dr As DiseñoRejilla = ld.Rejillas.Where(Function(x) x.Nombre = l.Name).First
                                    l.RestoreLayoutFromStream(New System.IO.MemoryStream(dr.Diseño))
                                End If
                            Catch ex As Exception
                                If Me.DelegadoErrorNoControlado IsNot Nothing Then Me.DelegadoErrorNoControlado.Invoke(Me, ex)
                                DXMessageBox.Show(ex.Message, "Error btDiseño_Itemclick")
                                'Debug.Write("Error DelegadoDiseño Rejilla")
                            End Try
                        Next
                        '  Dim drs = System.Text.Encoding.Unicode.GetBytes(tsl5.Utilidades.serializar(ld))
                    End If
                Catch ex As Exception
                    If Me.DelegadoErrorNoControlado IsNot Nothing Then Me.DelegadoErrorNoControlado.Invoke(Me, ex)

                    DXMessageBox.Show(ex.Message, "Error AbrirUclL - Diseño")
                    'Debug.Write("Error DelegadoDiseño AbrirUCCL")
                End Try
            End If
        Catch ex As Exception
            If Me.DelegadoErrorNoControlado IsNot Nothing Then Me.DelegadoErrorNoControlado.Invoke(Me, ex)
            DXMessageBox.Show(ex.Message, "Error AbrirUclL - Diseño")
        End Try
    End Sub

    Private Sub ApLin_PreviewKeyDown(sender As Object, e As KeyEventArgs)
        If e.Key = Key.Space Or e.Key = Key.Enter Then
            Try
                If Keyboard.FocusedElement.GetType = GetType(DevExpress.Xpf.Grid.RowIndicator) Or Keyboard.FocusedElement.GetType = GetType(DevExpress.Xpf.Editors.InplaceBaseEdit) Then
                    Dim cellData = DirectCast(DirectCast(sender, FrameworkElement).DataContext, EditGridCellData)
                    If cellData.Value IsNot Nothing AndAlso cellData.Value.ToString <> "" Then RaiseEvent Enlazar(cellData, True)
                End If
            Catch ex As Exception
            End Try
        End If
    End Sub

    'Sub LanzaEliminar(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)
    '    Throw New NotImplementedException
    'End Sub
    Sub Guardar()
        Try
            If Me.Contexto.GetType.GetInterfaces.Contains(GetType(ItsObjectContext)) Then
                DirectCast(Me.Contexto, ItsObjectContext).GuardarCambios()
            Else
                Me.Contexto.SaveChanges()
            End If

        Catch ex As Exception
            If DelegadoErrorNoControlado IsNot Nothing Then DelegadoErrorNoControlado.Invoke(Me, ex)
            DXMessageBox.Show(ex.Message, "Error Guardando")
        End Try
    End Sub

    Sub Eliminar()
        Try
            Me.Rejilla.View.CommitEditing()
            Dim bCancelar As Boolean = False
            Dim bEliminacionCorrecta As Boolean = False
            RaiseEvent AntesMensajeEliminar(bCancelar, bEliminacionCorrecta)
            If Not bCancelar Then
                If DXMessageBox.Show("¿Está seguro de querer eliminar los " & ElementosSeleccionados.GetSelectionCount.ToString & " registros seleccionados?", "Atención", MessageBoxButton.YesNo) = MessageBoxResult.Yes Then

                    'For Each k In ElementosSeleccionados.GetSelectedKeys
                    '    Me.IApLin.ObtieneContexto(Me.dcn).ExecuteStoreCommand("DELETE FROM " & Me.IApLin.NombreTablaBase & " WHERE " & Me.CampoIndice & "={0}", k)
                    'Next


                    For Each elemento In ElementosSeleccionados.GetSelectedrwh
                        '   RaiseEvent AntesEliminar(Rejilla.GetRowByListIndex(elemento))
                        bCancelar = False
                        RaiseEvent AntesEliminar(Rejilla.GetRow(elemento), bCancelar)
                        If Not bCancelar Then
                            Contexto.DeleteObject(Rejilla.GetRow(elemento))
                            If Contexto.GetType.GetInterfaces.Contains(GetType(ItsObjectContext)) Then
                                DirectCast(Contexto, ItsObjectContext).GuardarCambios()
                            Else
                                Contexto.SaveChanges()
                            End If

                        End If
                        ' RaiseEvent DespuesEliminar(elemento)
                    Next
                    ElementosSeleccionados = New SelectionHelper(Of Integer)
                    If AperturaAutomatica Then Me.Contexto.Connection.Open()
                    Try
                        Me.IApLin.EstableceDataContext(Me.uc.DataContext)
                    Catch ex As Exception
                        Try
                            If AperturaAutomatica Then Me.Contexto.Connection.Close()
                        Catch
                        End Try

                    End Try
                End If
            Else
                If bEliminacionCorrecta Then
                    ElementosSeleccionados = New SelectionHelper(Of Integer)
                    If AperturaAutomatica Then Me.Contexto.Connection.Open()
                    Try
                        Me.IApLin.EstableceDataContext(Me.uc.DataContext)
                    Catch ex As Exception
                        Try
                            If AperturaAutomatica Then Me.Contexto.Connection.Close()
                        Catch
                        End Try

                    End Try
                End If
            End If
        Catch ex As Exception
            If DXSplashScreen.IsActive Then DXSplashScreen.Close()
            If DelegadoErrorNoControlado IsNot Nothing Then DelegadoErrorNoControlado.Invoke(Me, ex)
            DXMessageBox.Show(ex.Message, "Error Eliminando")
        End Try
    End Sub


    'Private Sub dm_DockItemActivated(sender As Object, ea As Base.DockItemActivatedEventArgs) Handles dm.DockItemActivated
    '    If Refrescar Then Call RefrescaUC()
    'End Sub

    Public Sub Seleccionar(Celda As EditGridCellData)
        If Celda.Value IsNot Nothing AndAlso Celda.ToString <> "" Then RaiseEvent Enlazar(Celda, False)
    End Sub
    Public Sub SeleccionarIncluirNulosOVacios(Celda As EditGridCellData)
        RaiseEvent Enlazar(Celda, False)
    End Sub


    Sub LanzaEventoCargado()
        Dim gc As tsGridControl = Me.Rejilla.View.DataControl
        If gc.PropiedadesTSGC.EnlazarNulosOVacios Then
            gc.ComandoDelegado = New DelegateCommand(Of Object)(AddressOf SeleccionarIncluirNulosOVacios)
        Else
            gc.ComandoDelegado = New DelegateCommand(Of Object)(AddressOf Seleccionar)
        End If
        RaiseEvent Cargado()
        Me.ApCargado = True
    End Sub

    Sub SeleccionarHabilitadoCambiado(Habilitar As Boolean)
        Me.ContenedorL.Barsm.IsEnabled = Habilitar
        Me.Rejilla.Columns("tswpf_seleccionar").Visible = Habilitar
        Me.Rejilla.Columns("tswpf_seleccionar").VisibleIndex = 0
        Me.ContenedorL.btEliminar.IsEnabled = Me.PermisosConcedidos.Eliminar And ElementosSeleccionados.GetSelectionCount > 0 And Habilitar
        Me.ContenedorL.btInvertir.IsEnabled = Habilitar
        RaiseEvent SeleccionMultipleHabilitadoCambiado(Habilitar)
        '  Me.ContenedorL.btImprimirPlantilla.IsEnabled = Habilitar
        '  Me.ContenedorL.bePlantilla.IsEnabled = Habilitar
    End Sub

    Private Sub CustomUnboudColumnData(sender As Object, e As GridColumnDataEventArgs)
        If e.Column.FieldName = "tswpf_seleccionar" Then
            Dim key As Integer = CType(e.GetListSourceFieldValue(Me.CampoIndice), Integer)
            If e.IsGetData Then
                e.Value = ElementosSeleccionados.GetIsSelected(key)
            End If
            If e.IsSetData Then
                '  ElementosSeleccionados.SetIsSelected(e.Source.GetRowHandleByListIndex(e.ListSourceRowIndex), key, CBool(e.Value))
                ElementosSeleccionados.SetIsSelected(e.Source.GetRowHandleByListIndex(e.ListSourceRowIndex), key, CBool(e.Value))
                Me.ContenedorL.btEliminar.IsEnabled = Me.PermisosConcedidos.Eliminar And ElementosSeleccionados.GetSelectionCount > 0 And Me.ContenedorL.btSeleccionar.IsChecked = True
            End If
        End If
    End Sub

    Sub LanzaImprimirPlantilla(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs, idPlantilla As Integer)
        Me.Rejilla.View.CommitEditing()
        RaiseEvent ImprimirPlantilla(sender, e, idPlantilla)
    End Sub

    Sub LanzaEjecutarAccion(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs, idAccion As Integer)
        Me.Rejilla.View.CommitEditing()
        RaiseEvent EjecutarAccion(sender, e, idAccion)
    End Sub

    Public Sub RefrescaUC(Optional BackGround As Boolean = False, Optional IniciaContexto As Boolean = True)

        If IniciaContexto Then
            Try
                Me.Contexto = Me.IApLin.ObtieneContexto(Me.dcn)
            Catch ex As Exception
                Throw
            Finally
                Try
                    If Me.Contexto IsNot Nothing AndAlso AperturaAutomatica AndAlso Me.Contexto.Connection.State <> ConnectionState.Closed Then Me.Contexto.Connection.Close()
                Catch ex As Exception
                End Try
            End Try
        End If
        'If Not a.DeshabilitarRefresco Then
        '  Me.ContenedorL.t = Task.Run(New Action(Sub() Me.IApLin.EstableceDataContext(Me.uc.DataContext, BackGround)))
        '    If Not BackGround Then Me.ContenedorL.t.Wait()
        'End If
        Try
            '   Dim InicializaFilterPopupMode = (Me.Rejilla.ItemsSource Is Nothing)
            Me.IApLin.EstableceDataContext(Me.uc.DataContext, BackGround)
            tsGridControl.EstableceFilterPopupModePredeterminados(Me.Rejilla)
            If Me.ContenedorL.cbPlantillaAImprimir.ItemsSource Is Nothing OrElse Me.ContenedorL.cbPlantillaAImprimir.ItemsSource.Count = 0 OrElse Me.PermisosConcedidos.Impresion = False Then
                Me.ContenedorL.bePlantilla.IsVisible = False
                Me.ContenedorL.btImprimirPlantilla.IsVisible = False
            End If
            If Me.ContenedorL.cbAcciones.ItemsSource Is Nothing OrElse Me.ContenedorL.cbAcciones.ItemsSource.Count = 0 Then
                Me.ContenedorL.beAcciones.IsVisible = False
                Me.ContenedorL.btAcciones.IsVisible = False
            End If
            ElementosSeleccionados = New SelectionHelper(Of Integer)
            'Refrescar = False
            If Me.dlgCargado IsNot Nothing Then Me.dlgCargado.Invoke(Me)
        Catch ex As Exception
            If DelegadoErrorNoControlado IsNot Nothing Then DelegadoErrorNoControlado.Invoke(Me, ex)
            DXMessageBox.Show(ex.Message, "Error Refrescando")
        End Try
        RefrescoSolicitado = False
    End Sub

    Sub LanzaEventoInvertirSeleccion()
        RaiseEvent InvertirSeleccion()
    End Sub

    'Private Sub LanzaSeleccionarCambiado(sender As Object, e As EditorEventArgs)
    '    RaiseEvent SeleccionMultipleHabilitadoCambiado(True)
    'End Sub

    'Private Sub LanzaSeleccionarCambiado(sender As Object, e As CellValueChangedEventArgs)
    '    RaiseEvent SeleccionMultipleHabilitadoCambiado(True)
    'End Sub




    Private Sub Contexto_SavingChanges(sender As Object, e As EventArgs) Handles Contexto.SavingChanges
        If Me.DeshabilitarRefrescarOtrasPestañas = False Then Comun.RefrescaAplicaciones(Me.GrupoDocumentos.Parent, Nothing, Me.DocPanel.Tag)
    End Sub
End Class

