簡體   English   中英

如何在列表框中顯示可觀察集合的第一項?

[英]How will i show the first item of an observablecollection in a Listbox?

我有這個聲明:

    public ObservableCollection<SomeType> Collection { get; set; }

我嘗試了一些東西,例如:

    myListBox.ItemsSource = Collection[0];

在列表框控件中顯示“集合”的第一項 ,但它給出了錯誤。

我該怎么做? 我應該在右側進行哪些更改?

您需要將ItemSource綁定到您的集合,然后將所選索引設置為所需的索引(在您的情況下為0)

這是最小的例子。 XAML:

<Window x:Class="WPFSOTETS.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <ComboBox ItemsSource="{Binding Collection}" SelectedIndex="2"></ComboBox>
    </Grid>
</Window>

后面的代碼:

using System.Collections.ObjectModel;
using System.Windows;

namespace WPFSOTETS
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public ObservableCollection<string> Collection
        {
            get
            {
                return new ObservableCollection<string> {"one","two","three"};
            }
        }
    }
}

我將索引設置為2,只是為了好玩,但您可以使用它。


作為注釋,如果要在后台代碼中進行設置,則必須命名控件,然后可以從后台代碼中使用它並在此處進行綁定和設置。 例如,您可以看一下這個答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM