我有这个声明:
public ObservableCollection<SomeType> Collection { get; set; }
我尝试了一些东西,比如:
myListBox.ItemsSource = Collection[0];
在 Listbox 控件中显示 Collection 的第一项,但它给出了错误。
我将如何做到这一点?我应该在右侧做些什么改变?
我有这个声明:
public ObservableCollection<SomeType> Collection { get; set; }
我尝试了一些东西,比如:
myListBox.ItemsSource = Collection[0];
在 Listbox 控件中显示 Collection 的第一项,但它给出了错误。
我将如何做到这一点?我应该在右侧做些什么改变?
您需要将 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,只是为了好玩,但你可以玩它。
作为评论,如果你想在代码隐藏中设置它,你必须为你的控件命名,然后你可以从你的代码隐藏中使用它并在那里进行绑定和设置。例如,您可以查看此答案。