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

霸气de小男生 提交于 2019-11-29 03:34:41

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.

Try this

<ContentControl Content="{Binding YourCollection[0]}">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"></TextBlock>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!