views:

276

answers:

1

How do you remove the focus rectangle from a silverlight ListBox? I have this code:

<ListBox x:Name="MyListBox" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid >
               ...snipped...
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            <Setter Property="FocusVisualStyle" Value="{x:Null}" />
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

and when i run it i get the exception

System.Windows.Markup.XamlParseException: Invalid attribute value FocusVisualStyle for property Property. [Line: 47 Position: 38]

what am i doing wrong? Many thanks :)

A: 

In Silverlight the ListBoxItem type doesn't have a FocusVisualStyle property hence the error.

In order to acheive your goal you need to supply a new template for the ListBoxItem. Form the Silverlight documentation you'll find the default template in ListBox Styles and Templates.

Copy the ListBoxItem template into a Static resource (the App.Xaml would be a good place)

<ControlTemplate TargetType="ListBoxItem" x:Key="ListBoxItemSansFocus">
 <!-- copy of the rest of the control template here -->
</ControlTemplate>

Now remove the StoryBoard from the "Focused" VisualState and remove the final rectangle that has the name "FocusVisualElement".

Now in make your ContainerStyle property look like:-

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        <Setter Property="Template" Value="{StaticResource ListBoxItemSansFocus}" />
    </Style>
</ListBox.ItemContainerStyle>
AnthonyWJones