【发布时间】:2018-04-24 17:43:10
【问题描述】:
我有一个非常简单的ListView,其ItemsSource 是ObservableCollection。最好用代码来展示:
MainPage.xaml:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows.UI.Xaml.Shapes"
x:Class="Test.MainPage" Background="Black" >
<Grid x:Name="Board" Background="Transparent" >
<ListView ItemsSource="{x:Bind LineList}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Line">
<StackPanel Orientation="Horizontal" Spacing="5">
<TextBlock Foreground="White" Text="{x:Bind Name}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Mainpage.xaml.cs:
public sealed partial class MainPage : Page
{
public ObservableCollection<Line> LineList = new ObservableCollection<Line>();
public MainPage()
{
InitializeComponent();
LineList.CollectionChanged += List_CollectionChanged;
LineList.Add(new Line { Name = "Line1" });
LineList.Add(new Line { Name = "Line2" });
}
private void List_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if(e.Action == NotifyCollectionChangedAction.Add)
{
Board.Children.Add(e.NewItems[0] as Line);//if I comment out this line, no exception
}
}
}
我真正想要的是,当我在ListView 上添加Line 以显示它是Name 时,它也会作为实际Shape 添加到网格中。 请注意,我使用 ListView 仅显示这些行的名称,在网格中我想要一个实际的 Line 形状
我不知道我做错了什么,但上述尝试给出了声明的异常。
如果这些信息有帮助:
- 如果我不在
Grid中添加Line,不会出现异常 - 没有例外,如果:
Board.Children.Add(new Line { Name = "Line2" });
【问题讨论】:
-
什么是e.NewItems[0]?您在视图加载之前将项目添加到构造函数本身中,因此您可以检查项目或控件是否已形成。
-
还有一点,为什么 LineList 不是公共访问器类型?
-
好吧
LineList现在是公开的,但它没有帮助 -
让我直截了当地说,除了在
ListView中填充LineList项之外,您还想在网格中添加另一个元素吗? -
@Ale_lipa 我还想在网格中添加
Line元素,作为形状,它的名称在List
标签: c# exception uwp observablecollection