Chris Stewart
Chris Stewart

Reputation: 3303

Silverlight ListBox always highlights first item upon selection

I have a ListBox being populated in code. Each item is a simple text/url combination and when an item is selected, it should redirect to the selected item's URL. That is working as expected, but I'm having an issue with the selection of the item in the ListBox. It seems that no matter which item you selected, the first item in the ListBox is being highlighted each time. You are still taken to the correct item, but it's highlighting the wrong one. Any idea?

Edit: This is a problem in IE8, but works as expected in FF3.

Edit: Adding sample code. HeadlineData is a custom class, just basically to hold data to be displayed.

<Canvas x:Name="HeadlineCanvas">
    <ListBox x:Name="HeadlineListBox" Width="260" Height="380"  BorderBrush="Gainsboro" BorderThickness="1" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Hidden">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <HyperlinkButton MinHeight="20" MaxHeight="40" Width="240" NavigateUri="{Binding Url}" IsTabStop="False">
                        <TextBlock TextWrapping="Wrap" Text="{Binding Title}"/>
                    </HyperlinkButton>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Canvas>

C# Code

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();

        HeadlineData hd = new HeadlineData();
        hd.Title = "Title 1";
        hd.HeadlineNewsTitle = "Title 1";
        hd.LastModifiedTime = DateTime.Now;
        hd.Url = "http://www.google.com";

        this.HeadlineListBox.Items.Add(hd);

        hd = new HeadlineData();
        hd.Title = "Title 2";
        hd.HeadlineNewsTitle = "Title 2";
        hd.LastModifiedTime = DateTime.Now;
        hd.Url = "http://www.google.com";

        this.HeadlineListBox.Items.Add(hd);
    }
}

Upvotes: 0

Views: 1139

Answers (1)

Bryant
Bryant

Reputation: 8670

The problem is that your listbox isn't getting the selection. When you click on the Hyperlink button it is handling the click event so the item doesn't get selected.

You'll need to remove the hyperlink button and then do your navigation on the ListBox SelectionChanged event instead if you want the selection to change.

Upvotes: 2

Related Questions