Link to home
Start Free TrialLog in
Avatar of MrTouya
MrTouya

asked on

How do I select a listbox item by its tag in WPF and then disable it.

Hello Everyone,

I am trying to select a listbox item by its tag value and then disabling it. I have no clue on how to this wiht a WPF control. Can someone show me an example on how to achieve this?
Thanks,

Stephane
Avatar of itsmeandnobodyelse
itsmeandnobodyelse
Flag of Germany image

I found some sample code which may help.

private:
   void listBox1_SelectedIndexChanged( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      // Get the currently selected item in the ListBox.
      String^ curItem = listBox1->SelectedItem->ToString();

      // Find the string in ListBox2.
      int index = listBox2->FindString( curItem );

      // If the item was not found in ListBox 2 display a message box,
      //  otherwise select it in ListBox2.
      if ( index == -1 )
            MessageBox::Show( "Item is not available in ListBox2" );
      else
            listBox2->SetSelected( index, true );
   }
Avatar of MrTouya
MrTouya

ASKER

This is what I have to do now. Is there a better way of doing the same?
 

private void MenuButtonState(string MenuButtonName, string State)
{
ListBoxItem CurrentSelectedItem = (ListBoxItem)this.MenuButtons.SelectedItem;
ListBoxItem SelectionToChangeStateOf = (ListBoxItem)this.MenuButtons.FindName(MenuButtonName);
ItemCollection MenuItems = this.MenuButtons.Items;
int IndexToDisable = MenuItems.IndexOf((ListBoxItem)SelectionToChangeStateOf);
int CurrentSelectedIndex = MenuItems.IndexOf((ListBoxItem)CurrentSelectedItem);
MenuButtons.SelectedItem = IndexToDisable;
if (State == "Disabled")
SelectionToChangeStateOf.IsEnabled = false;
else SelectionToChangeStateOf.IsEnabled = true;
MenuButtons.SelectedItem = CurrentSelectedItem;
}
 
Thanks,
Does it work?

>>>> SelectionToChangeStateOf = (ListBoxItem)this.MenuButtons.FindName(MenuButtonName);

Does the FindName return a (reference to a) ListBoxItem or does it return an index? In the latter case you hardly could cast an integer to a ListBoxItem.
Avatar of MrTouya

ASKER

It Works. I have tried other ways, but this is the best way that I have come up with that works.
 
ASKER CERTIFIED SOLUTION
Avatar of itsmeandnobodyelse
itsmeandnobodyelse
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MrTouya

ASKER

Yep. That is much more elegant.

Thanks,