Saturday, August 1, 2009

"Binding" to ListBoxItem's IsSelected property from its template in Silverlight

It is not really a binding, but it does the trick:

<ListBox Name="MyListBox" ItemContainerStyle="{StaticResource MyListBoxItemStyle}" >

<Style x:Key="MyListBoxItemStyle" TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="Border" Padding="2" Loaded="Template_Loaded">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

private void Template_Loaded(object sender, RoutedEventArgs e)
{
Border border = (Border)sender;
ListBoxItem listBoxItem = (ListBoxItem)VisualTreeHelper.GetParent(border);

MyListBox.SelectionChanged +=
// this will be executed for every item whenever selection changes
delegate(object s1, SelectionChangedEventArgs e1)
{
if (listBoxItem.IsSelected)
{
// do stuff to "border" or "listBoxItem"
}
else
{
...
}
};
}

Labels: , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home