Search code examples
wpfbuttonisenabled

Disable buttons with similar NAMES


I have multiple buttons with similar names. Major similarity is the suffix _min. How can these all be disabled based upon the part of the name (and thus not based upon whole name?

btnX_min.IsEnabled = false;
btnY_min.IsEnabled = false;
btnZ_min.IsEnabled = false;

Needs to become:

for all buttons with string _min in Name, IsEnabled = false

How to accomplish?


Solution

  • Depending on where all these buttons are located in your Visual tree you might want to use the VisualTreeHelper class to be able to find all of them. Please refer to the recursive FindVisualChildren method here:

    Find all controls in WPF Window by type

    ...and try this:

    foreach (Button button in FindVisualChildren<Button>(this).Where(x => !string.IsNullOrEmpty(x.Name) && x.Name.Contains("_btn")))
        button.IsEnabled = false;