Search code examples
c#buttonexpression-blend

How to disable all buttons


I have a method that disables all the butttons on my window. But i can't seem to get the type of Button to match it to the Resource collection

I'm using Expression Blend 3 with a c# code-behind

void DisableButtons()
    {
        for(int i = 0; i>= this.Resources.Count -1; i ++)
        {
            if (this.Resources[i].GetType() == typeof(Button))
            {
                Button btn = (Button)this.Resources[i];
                btn.IsEnabled = false;
            }
        }

    }

Update

Thanks for the answers! Ok The loop is working but my code is incorrect. this.Resources Does not seem to include my buttons! This could be an Blend thing?

So Yeah. I ended up doing it manually. Cause I'm hasty and there isn't a short easy solution. Thanks for all the input though!


Solution

  • It is possible I misunderstood something, but you're trying to find Buttons CONTAINED in your window in the RESOURCES of your window? Because those two things are different things alltogether.
    If that is the case, either try setting this.IsEnabled = false (but that disables other things, not just buttons), or traverse the logical tree (or visual tree if silverlight) with LogicalTreeHelper/VisualTreeHelper, although that is a VERY expensive method.
    Manual workaround would be to give names to all your buttons, make a list of them in codebehind and iterate that list.

    However the best would be to create a boolean property called AreButtonsEnabled in your ViewModel (if you're not using MVVM than simply on the control itself - but make it DependencyProperty) and bind all your button's IsEnabled property to them! And then in codebehind simply set that boolean to false ... and magic ensues.

    If this is not your case then sorry I wasted your time.