How can I visibly collapse a single row in a Silverlight 4 ListBox without actually removing the row?
Working in C# and Silverlight 4, I am using a ListBox bound to a data source. At this time three items are in the data source and thus appear in the ListBox. I need the third item not to appear in the ListBox but still to exist otherwise for various reasons.
Let's say my ListBox instance is called myListBox.
Essentially what I'd like to be able to do is something like this:
myListBox.Rows[开发者_StackOverflow中文版2].Visibility = Visibility.Collapsed;
Perhaps a more general question I should be asking is: "How can I access individual rows in the ListBox and change the properties of each?"
Thank you.
You should hide elements in the collection you are binding to, not the control itself.
Make use of MVVM pattern and bind your ListBox to an observable collection in your viewmodel. It could be the observable collection of other viewodels if each item should support a lot of customizing. Then working with listbox becomes as easy as working with C# collections - you can perform any remove/add/hide logic without messing with control itself.
Edit:
Here's the idea of solution: you bind to ElementsVM
field, not to Elements
field. Elements
field is used to set the model for this instance of VM class. Later, when you need to hide/show an element, use something like _elementsVM[0].Visibility = Visibility.Collapsed
.
private ObservableCollection<Element> _elements;
public ObservableCollection Elements {
get { return _elements; }
set {
_elements = value;
var VMs = _elements.Select(el => new ElementVM(el, Visibility.Visible);
_elementsVM = new ObservableCollection<ElementVM>(VMs);
//NotifyPropertyChanged ("ElementVM")
}
}
privae ObserableCollection<ElementVM> _elementsVM;
public ObservableCollection ElementsVM {
get { return _elementsVM; }
}
public class ElementVM: INotifyPropertyChanged {
public Element Element { get; set; }
public Visibility IsVisible { get; set; }
public ElementVM (Element element, Visibility visibility) {
Element = element;
IsVisible = visibility;
}
// Implement INotifyPropertyChanged here
}
You'll have to work on my implementation of ElementVM
a little: make sure that PropertyChanged
is fired on setters and so on. You'll also need to bind IsVisible
property of item template to the IsVisible
property of ElementVM
.
精彩评论