开发者

Silverlight MVVM binding a ListBox

Using Silverlight 4 / MVVM.

I am trying to bind a ViewModel to a listbox with a custom template but the data is not displaying. I have managed to get raw data to display if I set the DisplayMemberPath property. If I remove this property and try and bind to the textblocks, nothing displays. Here is the XAML

 <ListBox Height='200'
             HorizontalAlignment='Left'
             Margin='10,10,0,0'
             Name='lstForumTopics'
             VerticalAlignment='Top'
             Width='200'
             DataContext='{Binding Path=ForumTopics,Source={StaticResource ForumViewModel}}'
             ItemsSource='{Binding Path=ForumTopics,Source={StaticResource ForumViewModel}}'>
        <ListBox.ItemTemplate>

            <DataTemplate>
                <StackPanel Orientation='Vertical'>
                    <TextBlock Text='{Binding ForumTopicText,Source={StaticResource ForumViewModel}}'></TextBlock>
                    <开发者_高级运维;TextBlock Text='{Binding PostCount,Source={StaticResource ForumViewModel}}'></TextBlock>
                </StackPanel>
            </DataTemplate>

        </ListBox.ItemTemplate>
        <ListBox.Background>
            <LinearGradientBrush EndPoint='0.5,1'
                                 StartPoint='0.5,0'>
                <GradientStop Color='#FFDCE2E5'
                              Offset='1' />
                <GradientStop Color='White'
                              Offset='0' />
            </LinearGradientBrush>
        </ListBox.Background>
    </ListBox>


I believe you are confusing the Binding engine. If you are going to use a StaticResource try...

DataContext="{Binding Source={StaticResource ForumViewModel}}"
ItemsSource="{Binding Path=ForumTopics}"

<TextBlock Text="{Binding Path=ForumTopicText}" />
<TextBlock Text="{Binding Path=PostCount}" />

A control has a DataContext which holds the object that the other properties will bind to. The ItemsSource just needs to know the property name of the DataContext object to bind to. Finally, the DataTemplate has a DataContext set to each of the objects within your item source, so they only need to be bound to the property name of the object within your ItemsSource.


I think you need to binding the ItemsSource of the ListBox to an ObservableCollection or IEnumerable of ForumViewModels, not just a single one.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜