如何在列表框中显示observablecollection的第一项?

时间:2013-12-05 00:35:49

标签: c# listbox observablecollection itemsource

我有这个声明:

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

我尝试了一些东西,比如:

    myListBox.ItemsSource = Collection[0];

在列表框控件中显示Collection的第一项,但它会出错。

我将如何做到这一点?我应该在右侧做出什么改变?

1 个答案:

答案 0 :(得分: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,只是为了好玩,但你可以玩它。


截至评论时,如果你想在代码隐藏中设置它,你必须为你的控件命名,然后你可以在你的代码隐藏中使用它,并在那里进行绑定和设置。例如,您可以查看this answer

相关问题