0

I've got a <menu> on my window which contains <TextBlock>, <Separator> and <MenuItem> within it and I need to loop through everything, only get the <MenuItem>, check its text value and hide it if it doesn't match text in my TextBox.

I've got the below code but it breaks when setting the item.Visibility as object does not contain a definition for 'Visibility'...:

    private void ItemsSearchBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        foreach(object item in ItemsMenu.Items)
        {
            Type type = item.GetType();
            if(type.Equals(typeof(MenuItem)))
            {
                var menuItemText_split = item.ToString().Split(' ', 1); 
                if (menuItemText_split[1].StartsWith(ItemsSearchBox.Text)) 
                { 
                    item.Visibility = Visibility.Collapsed; 
                }
            }
        }  
    }

I am doing the .Split() on the text due to it having a number displayed on the UI and I need to check the text after it. Luckily there is a space between the text I am after and the number, e.g. "1. TextIamAfter".

How can I make it so the item at the item.Visibility... part doesn't error?

Thanks,

Pawel
  • 141
  • 1
  • 10

1 Answers1

0

WPF is designed to support DataBinding. In your example, I suggest making your menu "data-driven". Rather than attempt to manipulate the menu items directly, you can bind the "items" of a menu to a list and your menu will automatically update if you modify that list. See How to correctly bind menu items? for an example.

LukeW
  • 43
  • 8