How to enable/disable all controls in a NSView?

GT85GT85 Member ✭✭

As it is not possible to enable/disable a NSView, I need to iterate on each control. But how? The cast from SubView to NSControl does not work.
Regards.

Tagged:

Answers

  • ChrisHamonsChrisHamons USForum Administrator, Xamarin Team Xamurai

    Recursively walking the subviews should work, but not all children will be NSControl, they all should be NSView though.

    Your question lacks sufficient information to be answerable, consider adding a code sample showing what you are trying to accomplish.

  • GT85GT85 Member ✭✭

    Hi Chris.
    Your answer has encouraged me to go on in this direction. I did a mistake by comparing types.
    Here is the good code, as far as I think.
    Regards.
    `

        /// <summary>
        /// Enables/disables all controls in a view.
        /// </summary>
        /// <param name="view">View to be enabled/disabled</param>
        /// <param name="enabled">If set to <c>true</c> enabled, else disabled.</param>
        private void EnableView(NSView view, bool enabled)
        {
            foreach (NSView sv in view.Subviews)
            {
                if (sv is NSControl)
                {
                    ((NSControl)sv).Enabled = enabled;
                }
                else
                {
                    EnableView(sv, enabled);
                }
            }   
        }
    

    `

  • ChrisHamonsChrisHamons USForum Administrator, Xamarin Team Xamurai

    Thanks for posting that for future users. It looks reasonably correct, but if you use the c# pattern matching it can be a bit more concise (untested):

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is#pattern-matching-with-is

    void EnableView(NSView view, bool enabled)
    {
        foreach (NSView sv in view.Subviews)
        {
            if (sv is NSControl c)
                c.Enabled = enabled;
            else
                EnableView(sv, enabled);
        }   
    }
    
Sign In or Register to comment.