开发者

Why selected item in ListBox throws error in expression blend?

I am learning expression blend using the following link http://visitmix.com/labs/rosetta/EyesOfBlend/DataTemplates/ It is a very good step by step instruction on using expression blend. I was able to do all the steps successfully and I was able to run the program and got the final result.

Right after step (9), before running the project, when I checked the designer, the designer did not show the image in the big image control I have added in step (9). I knew why, since the selected index of the ListBox was -1, so I changed the sel开发者_JAVA百科ectedindex to 0, now I was able to see the image. But when I compiled the code I get the following error

"Specified argument was out of the range of valid values. Parameter name:SelectedIndex"

XAML is

<Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource SampleDataSource}}">
    <Grid x:Name="itemGrid" DataContext="{Binding SelectedItem, ElementName=listBox}">
        <Image Margin="185,56,153,160" Stretch="Fill" Source="{Binding Name}"/>
    </Grid>
    <ListBox x:Name="listBox" SelectedIndex="0" Margin="8,0,0,8" ItemsSource="{Binding Collection}" ItemTemplate="{StaticResource ItemTemplate1}" ItemsPanel="{StaticResource ItemsPanelTemplate1}" Height="101" VerticalAlignment="Bottom"/>
</Grid>

If I remove the selected index, all compile good. Could someone explain why it showed first time after compiling, it stopped working?

Thanks


You are almost always better binding to the SelectedItem than the SelectedIndex. If the Item is null, the binding should fail gracefully.


This is probably because the "Collection" attribute gets bound to the itemsource after the listbox is rendered. So if there is no collection(empty) then the first index [0] does not exist and it throws an "out of range exception".

To resolve your issue set the selected index in code-behind after collection is populated. Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜