Julia
Julia

Reputation: 55

How do you hide a single listboxitem in a listbox using wpf codebehind?

I am creating a list box that holds notes. When a note is selected and double-clicked it opens an editing form. Here there is an option to archive the note. When the note is archived it should not be visible on the original form.

I have tried several things which can be seen below. I cannot seem to find a property that holds the visibility of a single item.

listBox.SelectedItem = Visibility.Collapsed;
listBox.SelectedItem.Visibility.Collapsed;

However they do not work. Any suggestions are appreciated!

Upvotes: 1

Views: 231

Answers (1)

Ben
Ben

Reputation: 86

Try the following:

((ListBoxItem)listBox.SelectedItem).Visibility = Visibility.Collapsed;

listBox.SelectedItem returns the item as an object. You need to type cast this to a ListBoxItem object it allows you to access all of the different properties of a listboxitem.

Hope this helps/works for you :)

* Edit *

The stack-overflow thread, typecasting in C#, should help to explain what I mean by casting. I will also try relate the answer from that thread to this problem.

Casting is usually a matter of telling the compiler that although it only knows that a value is of some general type, you know it's actually of a more specific type. For example:

// As previously mentioned, SelectedItem returns an object
object x = listBox.SelectedItem;

// We know that x really refers to a ListBoxItem so we can cast it to that.
// Here, the (ListBoxItem) is casting x to a ListBoxItem. 
ListBoxItem y = (ListBoxItem)x;

//This allows us to call the different methods and properties of a listbox item:
y.Visibility = Visibility.Collapsed;

//In my original answer I combined these three lines into one

Hopefully this helps to explain the answer in a bit more detail, there are also plenty of resources out there that can help explain type casting and objects in C# far better than!

Upvotes: 1

Related Questions