WPF: How to bind to only one item in a collection, not using ItemsControl since I don't want to display all of them

前端 未结 3 1061
-上瘾入骨i
-上瘾入骨i 2020-12-09 17:14

I have this requirement, that I have a collection of items (ObservableCollection), but I only want to display the first item. The requirement comes from the fact that in mos

相关标签:
3条回答
  • 2020-12-09 17:34

    To bind to just one item from a collection, you can use the following syntax:

    {Binding Items[0]}
    

    Or to bind to a property of a single item from the collection:

    {Binding Items[0].Property}
    

    You can find out more about property path syntax from the Binding.Path Property page at MSDN... from the linked page:

    • Indexers of a property can be specified within square brackets following the property name where the indexer is applied. For instance, the clause Path=ShoppingCart[0] sets the binding to the index that corresponds to how your property's internal indexing handles the literal string "0". Multiple indexers are also supported.

    0 讨论(0)
  • 2020-12-09 17:39

    Ok, late to the party but I thought I'd share my 2 cents anyway: I'd better go with a dumber (XAML-)view and a view-model closer to your presentation needs.

    Translated: instead of mapping your existing view-model (or raw data) and its collection of items directly to the view, I suggest to map that to an appropriate view-model showing something like a YourItemViewModel FirstItem property and a bool HasMore property. That second view-model would be easily unit-testable to make sure it behaves propertly, and would be easily mapped to a view with less logic, so to avoid possible hard-to-test problems in view.

    0 讨论(0)
  • 2020-12-09 17:40

    Try this

    <ContentControl Content="{Binding YourCollection[0]}">
        <ContentControl.ContentTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"></TextBlock>
            </DataTemplate>
        </ContentControl.ContentTemplate>
    </ContentControl>
    
    0 讨论(0)
提交回复
热议问题