简体   繁体   中英

Excel button is not disabled even when IsEnabled property is set to false

On button click I want the button clicked to be disabled and after executing a process re-enable it.

While it seems quite simple, for a reason the whole process executes successfully but the button is not disabled. It gets disabled on specific occasions and not in the start of the button click.

Below is the XAML code of the button

<Button 
    x:Name="PreviewReportButton"
    Click="PreviewExcelReportButton_Click"
    Background="{StaticResource ExportExcelButtonColor}"
    BorderBrush="{StaticResource ExportExcelButtonColor}"
    Focusable="False"
    IsEnabled="False"
    Width="80"
    Height="Auto"
    Margin="450,0,0,0"
    FontSize="9"
    FontWeight="DemiBold"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Grid.Column="3"
    Grid.Row="5"
    Cursor="Hand"
    VerticalContentAlignment="Center"
    HorizontalContentAlignment="Center">
    <TextBlock TextAlignment="Center">Button 1</TextBlock>
</Button>

The .cs file code in c# VS 2019

private void PreviewExcelReportButton_Click(object sender, RoutedEventArgs e)
{
    var btn_excel = (Button)sender;
    btn_excel.IsEnabled = false;
    //PreviewReportButton.IsEnabled = false; This is the same button as btn_excel (the button I want to click)

    Debug.WriteLine("Button must be disabled");

    try
    {
        //Check if file is open
        int IsMacroFileOpen = CheckFileIsOpen($@"{path}file_1.xlsm");
        int IsReportFileOpen = CheckFileIsOpen($@"{path}file_2.xlsm");
        int IsXLSXFileOpen = CheckFileIsOpen($@"{path}file_3.xlsx");

        Debug.WriteLine(IsMacroFileOpen);
        Debug.WriteLine(IsReportFileOpen);
        Debug.WriteLine(IsXLSXFileOpen);

        if (new[] { 1, 2 }.Contains(IsMacroFileOpen) || new[] { 1, 2 }.Contains(IsReportFileOpen) || new[] { 1, 2 }.Contains(IsXLSXFileOpen))
        {
            btn_excel.IsEnabled = true;
            return;
        }

        Mouse.OverrideCursor = Cursors.Wait;

        //Step 1: Create copy of standard report file
        CreateCopyReportServerNameDB($@"{path}file_1.xlsm");

        //Step 2: Run macro
        ExecuteExcelMacro($@"{path}file_2.xlsm");

        //Step 3: Open a copy of the xlsx updated file
        //Approach 1
        Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();

        ExcelApp.DisplayAlerts = false;
        ExcelApp.Visible = true;

        Microsoft.Office.Interop.Excel.Workbook ExcelWorkBook = ExcelApp.Workbooks.Add($"{path}file_3.xlsx");
    }
    catch (Exception)
    {
        this.Effect = new BlurEffect();
        bool? Result = new CustomMessageBox($"Unable to execute Excel button.\nPlease contact application support", "Error produced", MessageType.Error, MessageButtons.Ok).ShowDialog();
        if (Result.Value)
        {
            this.Effect = null;
            return;
        }
        else
        {
            this.Effect = null;
            return;
        }
    }
    finally
    {
        Mouse.OverrideCursor = null;
        btn.IsEnabled = true;
    }
}

Don't pay so much attention on what each method (CreateCopyReportServerNameDB, ExecuteExcelMacro) do because it's not relevant to the question. The whole functionality works. What does not work is the button disable on top of my code. When I click the button, the Cursor changes to Wait since I use Mouse.OverrideCursor = Cursors.Wait; . The weird thing is that the button is only disabled when a file is open which is catched by CheckFileIsOpen method. If no file is open the button is never disabled. And I am sure that I disable the button only on the top of the class and I renable it only at the end.

Also you will notice that I have put a Debug.Writeline to write if the IsEnabled = false; successfully executes and indeed the line is written as output. Although the button is never disabled unless a file is open and get caught by the mehtod CheckFileIsOpen .

Apologize that I reached the point to post a question for such a "dummy" think because to me it's obvious. But I cannot understand why this is happening to the IsEnabled of the button. Apologize if this is so simple, but I cannot figure out what is happening.

The problem seems to be when I execute the second method ExecuteExcelMacro The code of this method

public void ExecuteExcelMacro(string sourceFile)
{
    var destinationFile = @"file_1";
    Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();

    ExcelWorkBook = ExcelApp.Workbooks.Open(sourceFile);

    string macro = "ThisWorkbook.Run_Code";
    try
    {
        ExcelApp.Run(macro);
        Debug.WriteLine("Macro: " + macro + " executed successfully");
    }
    catch (Exception)
    {
        this.Effect = new BlurEffect();
        bool? Result = new CustomMessageBox($"Unable to Run Macro: {macro}", "Cannot execute Macro", MessageType.Error, MessageButtons.Ok).ShowDialog();
        if (Result.Value)
        {
            this.Effect = null;
            return;
        }
        else
        {
            this.Effect = null;
            return;
        }
        //Debug.WriteLine("Unable to Run Macro: " + macro + " Exception: " + ex.Message);
    }

    ExcelApp.DisplayAlerts = false;
    ExcelApp.Visible = false;

    ExcelWorkBook.SaveAs($@"{path}{destinationFile}", Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing);
    ExcelWorkBook.Close(0);
    ExcelApp.Quit();

    if (ExcelWorkBook != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelWorkBook); }
    if (ExcelApp != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp); }
}

In ExecuteExcelMacro() method, after creating an instance of ExcelApp make ExcelApp.ScreenUpdating=false; ExcelApp.Calculation=manual; ExcelApp.DisplayAlerts=false; ExcelApp.ScreenUpdating=false; ExcelApp.Calculation=manual; ExcelApp.DisplayAlerts=false; .

Don't made ExcelApp.Visible=false;

And in final block of PreviewExcelReportButton_Click() method, do Mouse.OverrideCursor = Cursors.Arrow;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM