How do I get a listbox template property for a currently selected item?
I have several list boxes, and a single a collection. The collection consists of structs, and each struct contains several color brushes. I set the source property of the list boxes to the collection and then in the template for each of the list boxes, bind the background property of a canvas to one of the brushes. Each list box displays different but complimentary colors in the same order.
My difficulty comes when I try and get the the selected color from a list box. The selected item is a struct and I cannot find a way of telling which color is being displayed. Here's some code to illustrate the problem:
<ListBox.ItemTemplate>
<DataTemplate>
<Canvas Background="{Binding colorBrush1}" Width="16" Height="16"/>
</Dat开发者_C百科aTemplate>
</ListBox.ItemTemplate>
How do I get to the template Canvas Background property for the currently selected item such that I can get the color of the currently selected item ?
Binding to brushes seems a little off to me. I'd bind the background to a "business object" using a ValueConverter to get the brush. Maybe you could pass in a parameter to the value converter which brush to retrieve from the struct.
As mentioned by foson, if you need the color of the current item, and that item is bound to some object which is providing the color, you should be able to get it directly from the business object.
As per your example, if you were binding to a listbox named MyListBox
a collection of MyObject
with a SolidColorBrush
property of colorBrush1
, then you would simply get the color of the selected item via ((MyObject)MyListBox.SelectedItem).colorBrush1.Color
.
That said, however, if you do need to then make changes to the visual item itself, or have any other need for knowing the generated UI controls (as I recently have had to do), then you can get the ListBoxItem
of the selected item by
var item = (ListBoxItem)MyListBox.ItemContainerGenerator.ContainerFromIndex(MyListBox.SelectedIndex);
精彩评论