我有一个 ListBox 并且想将它的 ItemsSource 设置为我从云中获取的 ObservableCollection。我必须等待这个传入的集合,它导致我的 itemssource 没有更新。
这是我的方法。这是我的 xaml.cs 构造函数:
{
InitializeComponent();
GetEmployeeList();
}
Run Code Online (Sandbox Code Playgroud)
以及它调用的方法:
private async void GetEmployeeList()
{
await EmployeeController.GetAllEmployees().ContinueWith(r =>
{
_employees = (r.Result);
EmployeeListBox.ItemsSource = _employees;
});
}
Run Code Online (Sandbox Code Playgroud)
我的 EmployeeController.GetAllEmployees() 返回一个 ObservableCollection。并且 _employees 得到更新,但是我的 EmployeeListBox 没有显示这些对象。我曾尝试使用静态硬编码集合,它运行良好 - 是因为我的异步吗?有人有建议吗?
- 谢谢。
嘿我有一个列表框,我将ItemsSource设置为我的数据库中的ObservableCollection对象,我需要在此列表的末尾添加一个对象.但是我一直收到无效的操作异常.不知怎的,我的列表框正在使用中(在我看来它是一个给定的,因为它显示并已经有内部的项目.)这是我的列表框的代码:
<ListBox x:Name="CarList" SelectionChanged="ItemSelected" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Background="{x:Null}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel FlowDirection="LeftToRight" ItemHeight="300" ItemWidth="300"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="10,10">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<Image Grid.Row="0" Source="{Binding image_path}" VerticalAlignment="Stretch"/>
<Grid Grid.Row="1" Background="SteelBlue">
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Margin="3" Text="{Binding model}"/>
<TextBlock HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3" Text="{Binding price}"/>
</Grid>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
我首先像这样设置ItemsSource:
CarList.ItemsSource = CarController.GetAllCars();
Run Code Online (Sandbox Code Playgroud)
然后想要添加我的自定义对象:
ListBoxItem carAdd = new ListBoxItem();
carAdd.Content = new CarModel{ image_path = "/../Assets/add-512.png", id=-1};
CarList.Items.Add(carAdd);
Run Code Online (Sandbox Code Playgroud)
但是,最后一次操作失败并显示以下消息:
使用ItemsSource时,操作无效.使用ItemsControl.ItemsSource访问和修改元素.
我已经找了一些其他的建议但是在他们的例子中都使用了字符串和单个绑定,因此我无法弄清楚到底要做什么.如果有人得到一个建议,将不胜感激.
- 谢谢.